Class: Script

Inherits:
Object
  • Object
show all
Includes:
Neo4jBolt
Defined in:
src/ruby/print-sus.rb,
src/ruby/mail-forwarder.rb,
src/ruby/mig-2021-09-05.rb,
src/ruby/create-nc-users.rb,
src/ruby/dump-lesson-info.rb,
src/ruby/share-nc-folders.rb,
src/ruby/create-nc-folders.rb,
src/ruby/archive-nc-folders.rb,
src/ruby/print-email-letters.rb,
src/ruby/mark-lehrbuchverein-paid.rb,
src/ruby/unshare-shares-to-klassen.rb,
src/ruby/write-matrix-corporal-policy.rb,
src/ruby/collect-nextcloud-files-from-sus.rb

Constant Summary collapse

CHARS =
'BCDFGHJKMNPQRSTVWXYZ23456789'.split('')
SPECIAL =
'-'.split('')

Instance Method Summary collapse

Constructor Details

#initializeScript

Returns a new instance of Script.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'src/ruby/mail-forwarder.rb', line 24

def initialize
#         @shutdown = false
#         Signal.trap("TERM") do 
#             STDERR.puts "Caught SIGTERM"
#             @shutdown = true
#         end
    @@schueler_for_klasse = Main.class_variable_get(:@@schueler_for_klasse)
    @@klassen_order = Main.class_variable_get(:@@klassen_order)
    @@teachers_for_klasse = Main.class_variable_get(:@@teachers_for_klasse)
    @@shorthands = Main.class_variable_get(:@@shorthands)
    @@user_info = Main.class_variable_get(:@@user_info)
    @@mailing_lists = nil
    @@mailing_list_mtime = 0
    begin
        imap = Net::IMAP.new(SCHUL_MAIL_LOGIN_IMAP_HOST)
    rescue
        STDERR.puts "Unable to resolve #{SCHUL_MAIL_LOGIN_IMAP_HOST}, exiting..."
        exit(1)
    end
    STDERR.puts "Mail forwarder ready with #{fresh_mailing_list().size} mailing lists at #{MAILING_LIST_EMAIL}!"
end

Instance Method Details

#allowed_sendersObject



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'src/ruby/mail-forwarder.rb', line 62

def allowed_senders()
    results = Set.new()
    results |= Set.new(@@user_info.keys.select { |email| @@user_info[email][:teacher] })
    results |= Set.new(SV_USERS)
    temp = $neo4j.neo4j_query(<<~END_OF_QUERY).map { |x| { :email => x['u.email'] } }
        MATCH (u:User {ev: true})
        RETURN u.email;
    END_OF_QUERY
    temp.each do |row|
        results << 'eltern.' + row[:email]
    end
    path = '/app/mail-forwarder-emails.txt'
    if File.exist?(path)
        File.open(path) do |f|
            f.each do |line|
                line.strip!
                next if line[0] == '#'
                results << line
            end
        end
    end
    @@klassen_order.each do |klasse|
        results << "ev.#{klasse}@mail.gymnasiumsteglitz.de"
    end
    results.map { |x| x.downcase }
end

#emit(s) ⇒ Object



7
8
9
# File 'src/ruby/create-nc-folders.rb', line 7

def emit(s)
    puts "__RUN__ #{s}"
end

#exit_if_not_exists(path) ⇒ Object



11
12
13
14
15
16
17
# File 'src/ruby/create-nc-folders.rb', line 11

def exit_if_not_exists(path)
    emit "if [ ! -d \"#{path}\" ]"
    emit "then"
    emit "    echo \"Path does not exist: #{path}\""
    emit "    exit 1"
    emit "fi"
end

#fresh_mailing_listObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'src/ruby/mail-forwarder.rb', line 46

def fresh_mailing_list()
    refresh = false
    path = '/internal/mailing_lists.yaml'
    if @@mailing_lists.nil?
        refresh = true
    elsif File.mtime(path) > @@mailing_list_mtime
        refresh = true
    end
    if refresh
        STDERR.puts "Re-reading mailing lists from disk..."
        @@mailing_list = YAML.load(File.read(path), aliases: true)
        @@mailing_list_mtime = File.mtime(path)
    end
    @@mailing_list
end

#gen_password_for_email(email) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'src/ruby/print-email-letters.rb', line 11

def gen_password_for_email(email)
    sha2 = Digest::SHA256.new()
    sha2 << EMAIL_PASSWORD_SALT
    sha2 << email
    srand(sha2.hexdigest.to_i(16))
    password = ''
    while true do
        if password =~ /[a-z]/ &&
        password =~ /[A-Z]/ &&
        password =~ /[0-9]/ &&
        password.include?('-')
            break
        end
        password = ''
        8.times do 
            c = CHARS.sample.dup
            c.downcase! if [0, 1].sample == 1
            password += c
        end
        password += '-'
        4.times do 
            c = CHARS.sample.dup
            c.downcase! if [0, 1].sample == 1
            password += c
        end
    end
    password
end

#generate_matrix_corporal_policyObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'src/ruby/write-matrix-corporal-policy.rb', line 19

def generate_matrix_corporal_policy
    result = {
        :schemaVersion => 1,
        :flags => {
            :allowCustomUserDisplayNames => false,
            :allowCustomUserAvatars => false,
            :allowCustomPassthroughUserPasswords => false,
            :allowUnauthenticatedPasswordResets => false,
            :forbidRoomCreation => false,
            :forbidEncryptedRoomCreation => false,
            :forbidUnencryptedRoomCreation => false
        },
        :managedCommunityIds => [],
        :managedRoomIds => [],
        :users => [],
        :hooks => [],
    }
    matrix_handle_to_email = {}
    stored_etags = {}
    temp = neo4j_query(<<~END_OF_QUERY)
        MATCH (u:User)
        RETURN u.email AS email, u.avatar_etag AS etag, u.avatar_etag_path AS etag_path;
    END_OF_QUERY
    temp.each do |row|
        stored_etags[row['email']] = {:etag => row['etag'], :path => row['etag_path']}
    end

    host = NEXTCLOUD_URL_FROM_RUBY_CONTAINER
    begin
        http = HTTP.persistent host
        @@user_info.each_pair do |email, info|
            handle = info[:matrix_login]
            matrix_handle_to_email[handle] = email
            stored_etag = stored_etags[email][:etag]
            stored_path = stored_etags[email][:path]
            
            user_entry = {
                :id => handle,
                :active => true,
                :authType => 'rest',
                :authCredential => "#{WEB_ROOT}/api/confirm_chat_login",
                :displayName => info[:teacher] ? info[:display_last_name] : info[:display_name],
                :joinedCommunityIds => [],
                :joinedRoomIds => [],
            }
            
            avatar_uri_nc = "#{NEXTCLOUD_URL_FROM_RUBY_CONTAINER}/index.php/avatar/#{info[:nc_login]}/512"
            STDERR.write '.'
            headers = {}
            if stored_etag && (stored_path.nil? || File.exist?(stored_path))
                headers['If-None-Match'] = stored_etag.split('.').first 
            end
            response = http.headers(headers).get("/index.php/avatar/#{info[:nc_login]}/512")
            etag = response.headers['ETag']
            raw_etag = etag.gsub('"', '')
            content_type = response.headers['Content-Type']
            ext = (content_type == 'image/png') ? 'png' : 'jpg'
            avatar_cache_path = "/gen/a/#{raw_etag[0, 2]}/#{raw_etag[2, raw_etag.size]}.#{ext}"
            if response.status.success?
                STDERR.puts "Re-caching #{avatar_uri_nc} to #{avatar_cache_path}"
                unless File::exist?(avatar_cache_path)
                    FileUtils::mkpath(File::dirname(avatar_cache_path))
                    File.open(avatar_cache_path, 'w') do |f|
                        f.write response.body
                    end
                end
                stored_etags[email] = {:etag => etag,
                                       :path => avatar_cache_path}
                temp = neo4j_query(<<~END_OF_QUERY, :email => email, :etag => etag, :path => avatar_cache_path)
                    MATCH (u:User {email: $email})
                    SET u.avatar_etag = $etag
                    SET u.avatar_etag_path = $path;
                END_OF_QUERY
                user_entry[:avatarUri] = "#{WEB_ROOT}#{avatar_cache_path}"
            else
                user_entry[:avatarUri] = WEB_ROOT + Dir["/gen/a/#{raw_etag[0, 2]}/#{raw_etag[2, raw_etag.size]}.*"].first
            end
            
            result[:users] << user_entry
        end
    ensure
        http.close if http
    end
        
    result[:hooks] << {
        :id => 'dashboard-hook-before-create-room',
        :eventType => 'beforeAuthenticatedRequest',
        :matchRules => [
            {:type => 'method', :regex => 'POST'},
            {:type => 'route', :regex => '^/_matrix/client/r0/createRoom'}
        ],
        :action => 'consult.RESTServiceURL',
        :RESTServiceURL => "#{WEB_ROOT}/api/matrix_hook",
        :RESTServiceRequestHeaders => {
            "Authorization" => "Bearer #{MATRIX_CORPORAL_CALLBACK_BEARER_TOKEN}",
        },
        :RESTServiceRequestTimeoutMilliseconds => 10000,
        :RESTServiceRetryAttempts => 1,
        :RESTServiceRetryWaitTimeMilliseconds => 5000
    }
    result[:hooks] << {
        :id => 'dashboard-hook-before-leave-room',
        :eventType => 'beforeAuthenticatedRequest',
        :matchRules => [
            {:type => 'method', :regex => 'POST'},
            {:type => 'route', :regex => '^/_matrix/client/r0/rooms/([^/]+)/leave'}
        ],
        :action => 'consult.RESTServiceURL',
        :RESTServiceURL => "#{WEB_ROOT}/api/matrix_hook",
        :RESTServiceRequestHeaders => {
            "Authorization" => "Bearer #{MATRIX_CORPORAL_CALLBACK_BEARER_TOKEN}",
        },
        :RESTServiceRequestTimeoutMilliseconds => 10000,
        :RESTServiceRetryAttempts => 1,
        :RESTServiceRetryWaitTimeMilliseconds => 5000
    }
    result[:hooks] << {
        :id => 'dashboard-hook-before-enable-encryption',
        :eventType => 'beforeAuthenticatedRequest',
        :matchRules => [
            {:type => 'method', :regex => 'PUT'},
            {:type => 'route', :regex => '^/_matrix/client/r0/rooms/([^/]+)/state/m.room.encryption/'}
        ],
        :action => 'consult.RESTServiceURL',
        :RESTServiceURL => "#{WEB_ROOT}/api/matrix_hook",
        :RESTServiceRequestHeaders => {
            "Authorization" => "Bearer #{MATRIX_CORPORAL_CALLBACK_BEARER_TOKEN}",
        },
        :RESTServiceRequestTimeoutMilliseconds => 10000,
        :RESTServiceRetryAttempts => 1,
        :RESTServiceRetryWaitTimeMilliseconds => 5000
    }
    result
end

#runObject



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'src/ruby/print-sus.rb', line 8

def run
    parser = Parser.new()
    entries = []

    parser.parse_schueler do |record|
        entries << {:email => record[:email],
                    :display_name => record[:display_name],
                    :display_first_name => record[:display_first_name],
                    :last_name => record[:last_name],
                    :display_last_name => record[:display_last_name],
                    :klasse => record[:klasse]
                   }
    end
    @@klassen_order = Main.class_variable_get(:@@klassen_order)
    entries.sort do |a, b|
        (a[:klasse] == b[:klasse]) ?
        ([a[:last_name], a[:display_first_name]].join('/') <=> [b[:last_name], b[:display_first_name]].join('/')) :
        ((@@klassen_order.index(a[:klasse]) || -1) <=> (@@klassen_order.index(b[:klasse]) || -1))
    end.each do |record|
        STDERR.puts "[#{record[:klasse]}] #{record[:display_name]} <#{record[:email]}>"
    end
end