# frozen_string_literal: true require 'faraday' require 'faraday_middleware' module Lhj class AppleAnalyticsHelper # @param [String] id: the app resource ID from the List Apps response. # @param [String] date: format YYYY-MM-DD # @param [String] conversation_id: robot conversation id def self.read_all_report(id, date, conversation_id) keys = [] url = "https://api.appstoreconnect.apple.com/v1/apps/#{id}/analyticsReportRequests" reports_res = Lhj::ConnectAPI.get(url) reports_res_body = JSON.parse(reports_res.body) reports_res_body['data'].each do |json| if json['attributes']['accessType'] == 'ONGOING' keys += read_reports(id, json['relationships']['reports']['links']['related'], date) end end notify(keys, conversation_id) if keys.length.positive? end # @return [Array] # @param [String] id # @param [String] url # @param [String] date def self.read_reports(id, url, date) keys = [] reports_res = Lhj::ConnectAPI.get(url) reports_res_body = JSON.parse(reports_res.body) reports_res_body['data'].each do |json| name = json['attributes']['name'].gsub(/\s/, '_') path = "analytics/#{id}/#{json['attributes']['category']}/#{name}/#{date}" keys += read_instances(json['relationships']['instances']['links']['related'], date, path) end keys end def self.read_instances(url, date, path) keys = [] req_url = "#{url}?filter%5BprocessingDate%5D=#{date}&filter%5Bgranularity%5D=DAILY" instances_res = Lhj::ConnectAPI.get(req_url) instances_res_body = JSON.parse(instances_res.body) instances_res_body['data'].each do |json| keys += read_segments(json['relationships']['segments']['links']['related'], path) end keys end def self.read_segments(url, path) keys = [] segment_res = Lhj::ConnectAPI.get(url) segment_res_body = JSON.parse(segment_res.body) segment_res_body['data'].each do |json| keys << download_csv(json['attributes']['url'], path) end keys end def self.download_csv(url, path) name = "#{rand(36 ** 8).to_s(36)}.csv.gz" key = "#{path}/#{name}" file = File.join(Lhj::Config.instance.home_dir, key) save_file(url, file) Lhj::OSS::Helper.instance.upload(key, file) File.delete(file) if File.exist?(file) key end def self.save_file(url, file) http_client = Faraday.new response = http_client.get(url) do |req| req.options[:timeout] = 300 req.options[:open_timeout] = 20 end FileUtils.mkdir_p(File.dirname(file)) unless File.directory?(File.dirname(file)) File.open(file, 'wb') { |fp| fp.write(response.body) } end def self.notify(keys, conversation_id) title = 'AppStore数据分析' markdown = "### 数据来源于App Store \n" keys.each do |k| a = k.split('/') name = a[3].gsub('_', ' ') markdown += "- [#{name}](#{Lhj::OSS::Helper.instance.object_url(k)}) \n" end Lhj::Dingtalk.send_markdown_message_with_api(conversation_id, title, markdown, '') end end end