CombinedText
stringlengths
4
3.42M
# frozen_string_literal: true class Audio::RecitationPresenter < BasePresenter RECITER_FIELDS = [ 'bio', 'profile_picture', 'cover_image' ] def recitations relation = Audio::Recitation .includes(:recitation_style, :qirat_type, reciter: :translated_name) .eager_load(reciter: :translated_name) .order('priority ASC, language_priority DESC') eager_load_translated_name filter_recitations(relation) end def reciter_fields strong_memoize :fields do if (fields = params[:fields]).presence fields.split(',').select do |field| RECITER_FIELDS.include?(field) end else [] end end end def approved_recitations recitations.approved end def recitation recitations.find_by(id: recitation_id) || raise_404("Recitation not found") end def recitation_without_eager_load Audio::Recitation.find_by(id: recitation_id) || raise_404("Recitation not found") end def approved_recitation approved_recitations.find_by(id: recitation_id) || raise_404("Recitation not found") end def related_recitations approved_recitations.where(id: recitation_without_eager_load.related_recitations) end def chapter_audio_file file = approved_audio_files.where(chapter_id: chapter.id).first file || raise_404("Sorry. Audio file for this surah is missing.") end def audio_files recitation_without_eager_load.chapter_audio_files end def approved_audio_files files = recitation_without_eager_load .chapter_audio_files .order('audio_chapter_audio_files.chapter_id ASC') if include_segments? files.includes(:audio_segments).order('audio_segments.verse_id ASC') else files end end def include_segments? chapter_id && include_in_response?(params[:segments].presence) end def chapter strong_memoize :chapter do if chapter_id Chapter.find_using_slug(chapter_id) || raise_404("Surah number or slug is invalid. Please select valid slug or surah number from 1-114.") else raise_404("Surah number or slug is invalid. Please select valid slug or surah number from 1-114.") end end end protected def chapter_id strong_memoize :chapter_id do id = params[:chapter_number] || params[:chapter_id] || params[:chapter] if id.present? id else if verse_id QuranUtils::Quran.get_chapter_id_from_verse_id(verse_id) end end end end def recitation_id params[:reciter_id] end def verse_id strong_memoize :verse_id do return params[:verse_id].to_i if params[:verse_id] if (key = params[:verse_key]) QuranUtils::Quran.get_ayah_id_from_key(key) end end end def filter_recitations(recitations) if params[:filter_reciter] recitations.where(reciter_id: params[:filter_reciter].to_i) else recitations end end end add chapter filter # frozen_string_literal: true class Audio::RecitationPresenter < BasePresenter RECITER_FIELDS = [ 'bio', 'profile_picture', 'cover_image' ] def recitations relation = Audio::Recitation .includes(:recitation_style, :qirat_type, reciter: :translated_name) .eager_load(reciter: :translated_name) .order('priority ASC, language_priority DESC') eager_load_translated_name filter_recitations(relation) end def reciter_fields strong_memoize :fields do if (fields = params[:fields]).presence fields.split(',').select do |field| RECITER_FIELDS.include?(field) end else [] end end end def approved_recitations recitations.approved end def recitation recitations.find_by(id: recitation_id) || raise_404("Recitation not found") end def recitation_without_eager_load Audio::Recitation.find_by(id: recitation_id) || raise_404("Recitation not found") end def approved_recitation approved_recitations.find_by(id: recitation_id) || raise_404("Recitation not found") end def related_recitations approved_recitations.where(id: recitation_without_eager_load.related_recitations) end def chapter_audio_file file = approved_audio_files.where(chapter_id: chapter.id).first file || raise_404("Sorry. Audio file for this surah is missing.") end def audio_files recitation_without_eager_load.chapter_audio_files end def approved_audio_files files = recitation_without_eager_load .chapter_audio_files .order('audio_chapter_audio_files.chapter_id ASC') files = if chapter_id files.where(chapter_id: chapter.id) else files end if include_segments? files.includes(:audio_segments).order('audio_segments.verse_id ASC') else files end end def include_segments? chapter_id && include_in_response?(params[:segments].presence) end def chapter strong_memoize :chapter do if chapter_id Chapter.find_using_slug(chapter_id) || raise_404("Surah number or slug is invalid. Please select valid slug or surah number from 1-114.") else raise_404("Surah number or slug is invalid. Please select valid slug or surah number from 1-114.") end end end protected def chapter_id strong_memoize :chapter_id do id = params[:chapter_number] || params[:chapter_id] || params[:chapter] if id.present? id else if verse_id QuranUtils::Quran.get_chapter_id_from_verse_id(verse_id) end end end end def recitation_id params[:reciter_id] end def verse_id strong_memoize :verse_id do return params[:verse_id].to_i if params[:verse_id] if (key = params[:verse_key]) QuranUtils::Quran.get_ayah_id_from_key(key) end end end def filter_recitations(recitations) if params[:filter_reciter] recitations.where(reciter_id: params[:filter_reciter].to_i) else recitations end end end
# # This is one of the new Tam Service Life Report classes # By profile class (RevenueVehicle, ServiceVehicle, Facility, Track) # class TrackTamServiceLifeReport < AbstractTamServiceLifeReport include FiscalYear COMMON_LABELS = ['Organization', 'Primary Mode', 'Line Length','TAM Policy Year','Goal Pcnt','Active Performance Restrictions', 'Pcnt', 'Avg Age', 'Avg TERM Condition'] COMMON_FORMATS = [:string, :string, :decimal, :fiscal_year, :percent, :decimal, :percent, :decimal, :decimal] def get_underlying_data(organization_id_list, params) query = Track.operational.joins(:infrastructure_segment_type, :infrastructure_division, :infrastructure_subdivision, :infrastructure_track) .joins('INNER JOIN organizations ON transam_assets.organization_id = organizations.id') .joins('INNER JOIN asset_subtypes ON transam_assets.asset_subtype_id = asset_subtypes.id') .joins('INNER JOIN fta_asset_categories ON transit_assets.fta_asset_category_id = fta_asset_categories.id') .joins('INNER JOIN fta_asset_classes ON transit_assets.fta_asset_class_id = fta_asset_classes.id') .joins('INNER JOIN fta_track_types ON transit_assets.fta_type_id = fta_track_types.id AND transit_assets.fta_type_type = "FtaTrackType"') .joins('LEFT JOIN (SELECT coalesce(SUM(extended_useful_life_months)) as sum_extended_eul, base_transam_asset_id FROM asset_events GROUP BY base_transam_asset_id) as rehab_events ON rehab_events.base_transam_asset_id = transam_assets.id') .joins('LEFT JOIN recent_asset_events_views AS recent_rating ON recent_rating.base_transam_asset_id = transam_assets.id AND recent_rating.asset_event_name = "ConditionUpdateEvent"') .joins('LEFT JOIN asset_events AS rating_event ON rating_event.id = recent_rating.asset_event_id') .joins('INNER JOIN assets_fta_mode_types ON assets_fta_mode_types.transam_asset_type = "Infrastructure" AND assets_fta_mode_types.transam_asset_id = infrastructures.id AND assets_fta_mode_types.is_primary=1') .joins('INNER JOIN fta_mode_types ON assets_fta_mode_types.fta_mode_type_id = fta_mode_types.id') .where(organization_id: organization_id_list) .where.not(transit_assets: {pcnt_capital_responsibility: nil, transit_assetible_type: 'TransitComponent', fta_type: FtaTrackType.where(name: ['Non-Revenue Service', 'Revenue Track - No Capital Replacement Responsibility'])}) asset_levels = fta_asset_category.asset_levels policy = TamPerformanceMetric .joins(tam_group: :tam_policy) .joins("INNER JOIN (SELECT tam_groups.organization_id, MAX(tam_policies.fy_year) AS max_fy_year FROM tam_groups INNER JOIN tam_policies ON tam_policies.id = tam_groups.tam_policy_id WHERE tam_groups.state IN ('activated') GROUP BY tam_groups.organization_id) AS max_tam_policy ON max_tam_policy.organization_id = tam_groups.organization_id AND max_tam_policy.max_fy_year = tam_policies_tam_groups.fy_year") .where(tam_groups: {state: ['pending_activation','activated']}).where(asset_level: asset_levels).select('tam_groups.organization_id', 'asset_level_id', 'max_fy_year', 'useful_life_benchmark', 'tam_groups.state', 'pcnt_goal') if policy.empty? cols = ['organizations.short_name', 'fta_asset_categories.name', 'fta_asset_classes.name', 'fta_track_types.name', 'asset_subtypes.name', 'CONCAT(fta_mode_types.code," - " ,fta_mode_types.name)','infrastructures.from_line', 'infrastructures.from_segment', 'infrastructures.to_line', 'infrastructures.to_segment', 'infrastructures.segment_unit', 'infrastructures.from_location_name', 'infrastructures.to_location_name', 'transam_assets.description', 'transam_assets.asset_tag', 'transam_assets.external_id', 'infrastructure_segment_types.name', 'infrastructure_divisions.name', 'infrastructure_subdivisions.name', 'infrastructure_tracks.name', 'transam_assets.in_service_date', 'transam_assets.purchase_date', 'transam_assets.purchase_cost', 'IF(transam_assets.purchased_new, "YES", "NO")', 'IF(IFNULL(sum_extended_eul, 0)>0, "YES", "NO")', 'IF(transit_assets.pcnt_capital_responsibility > 0, "YES", "NO")', 'infrastructures.max_permissible_speed', 'infrastructures.max_permissible_speed_unit','YEAR(CURDATE()) - YEAR(in_service_date)','rating_event.assessed_rating'] labels = ['Agency','Asset Category', 'Asset Class', 'Asset Type','Asset Subtype', 'Mode', 'Line','From', 'Line', 'To', 'Unit', 'From (location name)', 'To (location name)', 'Description / Segment Name', 'Asset / Segment ID', 'External ID', 'Segment Type', 'Main Line / Division', 'Branch / Subdivision', 'Track', 'In Service Date', 'Purchase Date', 'Purchase Cost', 'Purchased New', 'Rehabbed Asset?', 'Direct Capital Responsibility', 'Maximum Permissible Speed', 'Unit', 'Active Performance Restriction', 'Restriction Cause','Age', 'Current Condition (TERM)'] formats = [:string, :string, :string, :string, :string, :string, :string, :decimal, :string, :decimal, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :date, :date, :currency, :string, :string, :string, :integer, :string, :string, :string, :integer, :decimal] performance_restrictions_idx = -3 else query = query.joins("LEFT JOIN (#{policy.to_sql}) as ulbs ON ulbs.organization_id = transam_assets.organization_id AND ulbs.asset_level_id = transit_assets.fta_type_id AND fta_type_type = '#{asset_levels.first.class.name}'") cols = ['organizations.short_name', 'fta_asset_categories.name', 'fta_asset_classes.name', 'fta_track_types.name', 'asset_subtypes.name', 'CONCAT(fta_mode_types.code," - " ,fta_mode_types.name)','infrastructures.from_line', 'infrastructures.from_segment', 'infrastructures.to_line', 'infrastructures.to_segment', 'infrastructures.segment_unit', 'infrastructures.from_location_name', 'infrastructures.to_location_name', 'transam_assets.description', 'transam_assets.asset_tag', 'transam_assets.external_id', 'infrastructure_segment_types.name', 'infrastructure_divisions.name', 'infrastructure_subdivisions.name', 'infrastructure_tracks.name', 'transam_assets.in_service_date', 'transam_assets.purchase_date', 'transam_assets.purchase_cost', 'IF(transam_assets.purchased_new, "YES", "NO")', 'IF(IFNULL(sum_extended_eul, 0)>0, "YES", "NO")', 'IF(transit_assets.pcnt_capital_responsibility > 0, "YES", "NO")', 'infrastructures.max_permissible_speed', 'infrastructures.max_permissible_speed_unit',"IFNULL(max_fy_year,'')","IFNULL(pcnt_goal,'')",'YEAR(CURDATE()) - YEAR(in_service_date)','rating_event.assessed_rating'] labels = ['Agency','Asset Category', 'Asset Class', 'Asset Type','Asset Subtype', 'Mode', 'Line','From', 'Line', 'To', 'Unit', 'From (location name)', 'To (location name)', 'Description / Segment Name', 'Asset / Segment ID', 'External ID', 'Segment Type', 'Main Line / Division', 'Branch / Subdivision', 'Track', 'In Service Date', 'Purchase Date', 'Purchase Cost', 'Purchased New', 'Rehabbed Asset?', 'Direct Capital Responsibility', 'Maximum Permissible Speed', 'Unit', 'Active Performance Restriction', 'Restriction Cause', 'TAM Policy Year','Goal Pcnt','Age', 'Current Condition (TERM)'] formats = [:string, :string, :string, :string, :string, :string, :string, :decimal, :string, :decimal, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :date, :date, :currency, :string, :string, :string, :integer, :string, :string, :string, :fiscal_year, :percent, :integer, :decimal] performance_restrictions_idx = -5 end data = query.order('infrastructures.id').pluck(*cols) new_data = [] Track.operational.where.not(transit_assets: {pcnt_capital_responsibility: nil, transit_assetible_type: 'TransitComponent', fta_type: FtaTrackType.where(name: ['Non-Revenue Service', 'Revenue Track - No Capital Replacement Responsibility'])}).order(:id).each_with_index do |row, idx| active_restrictions = row.linked_performance_restriction_updates PerformanceRestrictionUpdateEvent.running.where(transam_asset_id: x.get_segmentable_with_like_line_attributes(include_self: true).pluck(:id)).select{ |event| overlaps(event) } new_data << data[idx][0..performance_restrictions_idx] + [active_restrictions.count > 0 ? 'Yes' : 'No', active_restrictions.count > 1 ? 'Multiple' : active_restrictions.first.try(:performance_restriction_type).try(:to_s)] + data[idx][performance_restrictions_idx+1..-1] end return {labels: labels, data: new_data, formats: formats} end def initialize(attributes = {}) super(attributes) end def get_data(organization_id_list, params) data = [] single_org_view = params[:has_organization].to_i == 1 || organization_id_list.count == 1 query = Track.operational.joins(transit_asset: [{transam_asset: :organization}, :fta_asset_class]) .joins('INNER JOIN assets_fta_mode_types ON assets_fta_mode_types.transam_asset_type = "Infrastructure" AND assets_fta_mode_types.transam_asset_id = infrastructures.id AND assets_fta_mode_types.is_primary=1') .joins('INNER JOIN fta_mode_types ON assets_fta_mode_types.fta_mode_type_id = fta_mode_types.id') .where(organization_id: organization_id_list) .where.not(transit_assets: {pcnt_capital_responsibility: nil, transit_assetible_type: 'TransitComponent', fta_type: FtaTrackType.where(name: ['Non-Revenue Service', 'Revenue Track - No Capital Replacement Responsibility'])}) tam_data = grouped_activated_tam_performance_metrics(organization_id_list, fta_asset_category, single_org_view, query.group('organizations.short_name', 'CONCAT(fta_mode_types.code," - " ,fta_mode_types.name)').count) if single_org_view grouped_query = query.group('organizations.short_name') else grouped_query = query end grouped_query = grouped_query.group('CONCAT(fta_mode_types.code," - " ,fta_mode_types.name)') assets_count = grouped_query.distinct.count('transam_assets.id') weather_performance_restriction = PerformanceRestrictionType.find_by(name: 'Weather') line_lengths = Hash.new restriction_lengths = Hash.new assets_count.keys.each do |mode| total_restriction_segment = 0 total_asset_segment = 0 query.where(fta_mode_types: {code: (single_org_view ? mode.last : mode).split('-')[0].strip}).get_lines.each do |line| total_restriction_segment += PerformanceRestrictionUpdateEvent.where(transam_asset: line).where.not(performance_restriction_type: weather_performance_restriction, state: 'expired').total_segment_length total_asset_segment += line.total_segment_length end line_lengths[mode] = total_asset_segment restriction_lengths[mode] = total_restriction_segment end total_age = grouped_query.sum('YEAR(CURDATE()) - YEAR(in_service_date)') assets_count.each do |k, v| assets = query.where(fta_mode_types: {name: (single_org_view ? k.last : k).split('-').last.strip}, organization_id: organization_id_list).where.not(transit_assets: {pcnt_capital_responsibility: nil, transit_assetible_type: 'TransitComponent', fta_type: FtaTrackType.where(name: ['Non-Revenue Service', 'Revenue Track - No Capital Replacement Responsibility'])}) condition_events = ConditionUpdateEvent .where(id: AssetEvent .where(base_transam_asset_id: assets.select('transam_assets.id'), asset_event_type_id: AssetEventType .find_by(class_name: 'ConditionUpdateEvent')) .group(:base_transam_asset_id).maximum(:id).values) condition_events_count = condition_events.count row = (single_org_view ? [] : ['All (Filtered) Organizations']) + [*k, line_lengths[k], tam_data[k] ? TamPolicy.first.try(:fy_year) : nil, (tam_data[k] || [])[1], restriction_lengths[k], line_lengths[k] > 0 ? (restriction_lengths[k]*100.0/line_lengths[k] + 0.5).to_i : '', (total_age[k]/v.to_f).round(2), condition_events_count > 0 ? condition_events.sum(:assessed_rating)/condition_events_count.to_f : '' ] data << row end return {labels: COMMON_LABELS, data: data, formats: COMMON_FORMATS} end def fta_asset_category @fta_asset_category ||= FtaAssetCategory.find_by(name: 'Infrastructure') end end typo - syntax error # # This is one of the new Tam Service Life Report classes # By profile class (RevenueVehicle, ServiceVehicle, Facility, Track) # class TrackTamServiceLifeReport < AbstractTamServiceLifeReport include FiscalYear COMMON_LABELS = ['Organization', 'Primary Mode', 'Line Length','TAM Policy Year','Goal Pcnt','Active Performance Restrictions', 'Pcnt', 'Avg Age', 'Avg TERM Condition'] COMMON_FORMATS = [:string, :string, :decimal, :fiscal_year, :percent, :decimal, :percent, :decimal, :decimal] def get_underlying_data(organization_id_list, params) query = Track.operational.joins(:infrastructure_segment_type, :infrastructure_division, :infrastructure_subdivision, :infrastructure_track) .joins('INNER JOIN organizations ON transam_assets.organization_id = organizations.id') .joins('INNER JOIN asset_subtypes ON transam_assets.asset_subtype_id = asset_subtypes.id') .joins('INNER JOIN fta_asset_categories ON transit_assets.fta_asset_category_id = fta_asset_categories.id') .joins('INNER JOIN fta_asset_classes ON transit_assets.fta_asset_class_id = fta_asset_classes.id') .joins('INNER JOIN fta_track_types ON transit_assets.fta_type_id = fta_track_types.id AND transit_assets.fta_type_type = "FtaTrackType"') .joins('LEFT JOIN (SELECT coalesce(SUM(extended_useful_life_months)) as sum_extended_eul, base_transam_asset_id FROM asset_events GROUP BY base_transam_asset_id) as rehab_events ON rehab_events.base_transam_asset_id = transam_assets.id') .joins('LEFT JOIN recent_asset_events_views AS recent_rating ON recent_rating.base_transam_asset_id = transam_assets.id AND recent_rating.asset_event_name = "ConditionUpdateEvent"') .joins('LEFT JOIN asset_events AS rating_event ON rating_event.id = recent_rating.asset_event_id') .joins('INNER JOIN assets_fta_mode_types ON assets_fta_mode_types.transam_asset_type = "Infrastructure" AND assets_fta_mode_types.transam_asset_id = infrastructures.id AND assets_fta_mode_types.is_primary=1') .joins('INNER JOIN fta_mode_types ON assets_fta_mode_types.fta_mode_type_id = fta_mode_types.id') .where(organization_id: organization_id_list) .where.not(transit_assets: {pcnt_capital_responsibility: nil, transit_assetible_type: 'TransitComponent', fta_type: FtaTrackType.where(name: ['Non-Revenue Service', 'Revenue Track - No Capital Replacement Responsibility'])}) asset_levels = fta_asset_category.asset_levels policy = TamPerformanceMetric .joins(tam_group: :tam_policy) .joins("INNER JOIN (SELECT tam_groups.organization_id, MAX(tam_policies.fy_year) AS max_fy_year FROM tam_groups INNER JOIN tam_policies ON tam_policies.id = tam_groups.tam_policy_id WHERE tam_groups.state IN ('activated') GROUP BY tam_groups.organization_id) AS max_tam_policy ON max_tam_policy.organization_id = tam_groups.organization_id AND max_tam_policy.max_fy_year = tam_policies_tam_groups.fy_year") .where(tam_groups: {state: ['pending_activation','activated']}).where(asset_level: asset_levels).select('tam_groups.organization_id', 'asset_level_id', 'max_fy_year', 'useful_life_benchmark', 'tam_groups.state', 'pcnt_goal') if policy.empty? cols = ['organizations.short_name', 'fta_asset_categories.name', 'fta_asset_classes.name', 'fta_track_types.name', 'asset_subtypes.name', 'CONCAT(fta_mode_types.code," - " ,fta_mode_types.name)','infrastructures.from_line', 'infrastructures.from_segment', 'infrastructures.to_line', 'infrastructures.to_segment', 'infrastructures.segment_unit', 'infrastructures.from_location_name', 'infrastructures.to_location_name', 'transam_assets.description', 'transam_assets.asset_tag', 'transam_assets.external_id', 'infrastructure_segment_types.name', 'infrastructure_divisions.name', 'infrastructure_subdivisions.name', 'infrastructure_tracks.name', 'transam_assets.in_service_date', 'transam_assets.purchase_date', 'transam_assets.purchase_cost', 'IF(transam_assets.purchased_new, "YES", "NO")', 'IF(IFNULL(sum_extended_eul, 0)>0, "YES", "NO")', 'IF(transit_assets.pcnt_capital_responsibility > 0, "YES", "NO")', 'infrastructures.max_permissible_speed', 'infrastructures.max_permissible_speed_unit','YEAR(CURDATE()) - YEAR(in_service_date)','rating_event.assessed_rating'] labels = ['Agency','Asset Category', 'Asset Class', 'Asset Type','Asset Subtype', 'Mode', 'Line','From', 'Line', 'To', 'Unit', 'From (location name)', 'To (location name)', 'Description / Segment Name', 'Asset / Segment ID', 'External ID', 'Segment Type', 'Main Line / Division', 'Branch / Subdivision', 'Track', 'In Service Date', 'Purchase Date', 'Purchase Cost', 'Purchased New', 'Rehabbed Asset?', 'Direct Capital Responsibility', 'Maximum Permissible Speed', 'Unit', 'Active Performance Restriction', 'Restriction Cause','Age', 'Current Condition (TERM)'] formats = [:string, :string, :string, :string, :string, :string, :string, :decimal, :string, :decimal, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :date, :date, :currency, :string, :string, :string, :integer, :string, :string, :string, :integer, :decimal] performance_restrictions_idx = -3 else query = query.joins("LEFT JOIN (#{policy.to_sql}) as ulbs ON ulbs.organization_id = transam_assets.organization_id AND ulbs.asset_level_id = transit_assets.fta_type_id AND fta_type_type = '#{asset_levels.first.class.name}'") cols = ['organizations.short_name', 'fta_asset_categories.name', 'fta_asset_classes.name', 'fta_track_types.name', 'asset_subtypes.name', 'CONCAT(fta_mode_types.code," - " ,fta_mode_types.name)','infrastructures.from_line', 'infrastructures.from_segment', 'infrastructures.to_line', 'infrastructures.to_segment', 'infrastructures.segment_unit', 'infrastructures.from_location_name', 'infrastructures.to_location_name', 'transam_assets.description', 'transam_assets.asset_tag', 'transam_assets.external_id', 'infrastructure_segment_types.name', 'infrastructure_divisions.name', 'infrastructure_subdivisions.name', 'infrastructure_tracks.name', 'transam_assets.in_service_date', 'transam_assets.purchase_date', 'transam_assets.purchase_cost', 'IF(transam_assets.purchased_new, "YES", "NO")', 'IF(IFNULL(sum_extended_eul, 0)>0, "YES", "NO")', 'IF(transit_assets.pcnt_capital_responsibility > 0, "YES", "NO")', 'infrastructures.max_permissible_speed', 'infrastructures.max_permissible_speed_unit',"IFNULL(max_fy_year,'')","IFNULL(pcnt_goal,'')",'YEAR(CURDATE()) - YEAR(in_service_date)','rating_event.assessed_rating'] labels = ['Agency','Asset Category', 'Asset Class', 'Asset Type','Asset Subtype', 'Mode', 'Line','From', 'Line', 'To', 'Unit', 'From (location name)', 'To (location name)', 'Description / Segment Name', 'Asset / Segment ID', 'External ID', 'Segment Type', 'Main Line / Division', 'Branch / Subdivision', 'Track', 'In Service Date', 'Purchase Date', 'Purchase Cost', 'Purchased New', 'Rehabbed Asset?', 'Direct Capital Responsibility', 'Maximum Permissible Speed', 'Unit', 'Active Performance Restriction', 'Restriction Cause', 'TAM Policy Year','Goal Pcnt','Age', 'Current Condition (TERM)'] formats = [:string, :string, :string, :string, :string, :string, :string, :decimal, :string, :decimal, :string, :string, :string, :string, :string, :string, :string, :string, :string, :string, :date, :date, :currency, :string, :string, :string, :integer, :string, :string, :string, :fiscal_year, :percent, :integer, :decimal] performance_restrictions_idx = -5 end data = query.order('infrastructures.id').pluck(*cols) new_data = [] Track.operational.where.not(transit_assets: {pcnt_capital_responsibility: nil, transit_assetible_type: 'TransitComponent', fta_type: FtaTrackType.where(name: ['Non-Revenue Service', 'Revenue Track - No Capital Replacement Responsibility'])}).order(:id).each_with_index do |row, idx| active_restrictions = row.linked_performance_restriction_updates PerformanceRestrictionUpdateEvent.running.where(transam_asset_id: row.get_segmentable_with_like_line_attributes(include_self: true).pluck(:id)).select{ |event| overlaps(event) } new_data << data[idx][0..performance_restrictions_idx] + [active_restrictions.count > 0 ? 'Yes' : 'No', active_restrictions.count > 1 ? 'Multiple' : active_restrictions.first.try(:performance_restriction_type).try(:to_s)] + data[idx][performance_restrictions_idx+1..-1] end return {labels: labels, data: new_data, formats: formats} end def initialize(attributes = {}) super(attributes) end def get_data(organization_id_list, params) data = [] single_org_view = params[:has_organization].to_i == 1 || organization_id_list.count == 1 query = Track.operational.joins(transit_asset: [{transam_asset: :organization}, :fta_asset_class]) .joins('INNER JOIN assets_fta_mode_types ON assets_fta_mode_types.transam_asset_type = "Infrastructure" AND assets_fta_mode_types.transam_asset_id = infrastructures.id AND assets_fta_mode_types.is_primary=1') .joins('INNER JOIN fta_mode_types ON assets_fta_mode_types.fta_mode_type_id = fta_mode_types.id') .where(organization_id: organization_id_list) .where.not(transit_assets: {pcnt_capital_responsibility: nil, transit_assetible_type: 'TransitComponent', fta_type: FtaTrackType.where(name: ['Non-Revenue Service', 'Revenue Track - No Capital Replacement Responsibility'])}) tam_data = grouped_activated_tam_performance_metrics(organization_id_list, fta_asset_category, single_org_view, query.group('organizations.short_name', 'CONCAT(fta_mode_types.code," - " ,fta_mode_types.name)').count) if single_org_view grouped_query = query.group('organizations.short_name') else grouped_query = query end grouped_query = grouped_query.group('CONCAT(fta_mode_types.code," - " ,fta_mode_types.name)') assets_count = grouped_query.distinct.count('transam_assets.id') weather_performance_restriction = PerformanceRestrictionType.find_by(name: 'Weather') line_lengths = Hash.new restriction_lengths = Hash.new assets_count.keys.each do |mode| total_restriction_segment = 0 total_asset_segment = 0 query.where(fta_mode_types: {code: (single_org_view ? mode.last : mode).split('-')[0].strip}).get_lines.each do |line| total_restriction_segment += PerformanceRestrictionUpdateEvent.where(transam_asset: line).where.not(performance_restriction_type: weather_performance_restriction, state: 'expired').total_segment_length total_asset_segment += line.total_segment_length end line_lengths[mode] = total_asset_segment restriction_lengths[mode] = total_restriction_segment end total_age = grouped_query.sum('YEAR(CURDATE()) - YEAR(in_service_date)') assets_count.each do |k, v| assets = query.where(fta_mode_types: {name: (single_org_view ? k.last : k).split('-').last.strip}, organization_id: organization_id_list).where.not(transit_assets: {pcnt_capital_responsibility: nil, transit_assetible_type: 'TransitComponent', fta_type: FtaTrackType.where(name: ['Non-Revenue Service', 'Revenue Track - No Capital Replacement Responsibility'])}) condition_events = ConditionUpdateEvent .where(id: AssetEvent .where(base_transam_asset_id: assets.select('transam_assets.id'), asset_event_type_id: AssetEventType .find_by(class_name: 'ConditionUpdateEvent')) .group(:base_transam_asset_id).maximum(:id).values) condition_events_count = condition_events.count row = (single_org_view ? [] : ['All (Filtered) Organizations']) + [*k, line_lengths[k], tam_data[k] ? TamPolicy.first.try(:fy_year) : nil, (tam_data[k] || [])[1], restriction_lengths[k], line_lengths[k] > 0 ? (restriction_lengths[k]*100.0/line_lengths[k] + 0.5).to_i : '', (total_age[k]/v.to_f).round(2), condition_events_count > 0 ? condition_events.sum(:assessed_rating)/condition_events_count.to_f : '' ] data << row end return {labels: COMMON_LABELS, data: data, formats: COMMON_FORMATS} end def fta_asset_category @fta_asset_category ||= FtaAssetCategory.find_by(name: 'Infrastructure') end end
require 'rails_best_practices/checks/check' module RailsBestPractices module Checks class KeepFindersOnTheirOwnModelCheck < Check def interesting_nodes [:call] end def interesting_files /models\/.*rb/ end def evaluate_start(node) add_error "keep finders on their own model" if others_finder?(node) end private def others_finder?(node) node.message == :find and node.subject.node_type == :call end end end end add comment to keep_finders_on_their_own_model_check require 'rails_best_practices/checks/check' module RailsBestPractices module Checks # Check a model to make sure finders are on their own model. # # Implementation: check if :find is called by other model. class KeepFindersOnTheirOwnModelCheck < Check def interesting_nodes [:call] end def interesting_files /models\/.*rb/ end def evaluate_start(node) add_error "keep finders on their own model" if others_finder?(node) end private def others_finder?(node) node.message == :find and node.subject.node_type == :call end end end end
1, As Order Taker shared examples. shared_examples 'Unidom::Order::Concerns::AsOrderTaker' do |model_attributes| context do order_1_attributes = { placer_id: SecureRandom.uuid, placer_type: 'Unidom::Order::Placer::Mock', number: SecureRandom.hex(6), purchase_amount: 10.00, aggregate_amount: 10.00 } order_1_attributes = { placer_id: SecureRandom.uuid, placer_type: 'Unidom::Order::Placer::Mock', number: SecureRandom.hex(6), purchase_amount: 20.00, aggregate_amount: 20.00 } it_behaves_like 'has_many', model_attributes, :taken_orders, Unidom::Order::Order, [ order_1_attributes, order_1_attributes ] end end
module TranslationIO class Client class SyncOperation < BaseOperation class ApplyYamlSourceEditsStep def initialize(yaml_file_paths, source_locale) @yaml_file_paths = yaml_file_paths @source_locale = source_locale end def run(params) TranslationIO.info "Downloading YAML source editions." params.merge!({ :timestamp => metadata_timestamp }) parsed_response = perform_source_edits_request(params) unless parsed_response.nil? TranslationIO.info "Applying YAML source editions." parsed_response['source_edits'].each do |source_edit| inserted = false sort_by_project_locales_first(@yaml_file_paths).each do |file_path| yaml_hash = YAML::load(File.read(file_path)) flat_yaml_hash = FlatHash.to_flat_hash(yaml_hash) flat_yaml_hash.each do |key, value| if key == "#{@source_locale}.#{source_edit['key']}" if value == source_edit['old_text'] TranslationIO.info "#{source_edit['key']} | #{source_edit['old_text']} -> #{source_edit['new_text']}", 2, 2 if locale_file_path_in_project?(file_path) flat_yaml_hash[key] = source_edit['new_text'] file_content = to_hash_to_yaml(flat_yaml_hash) File.open(file_path, 'w') do |f| f.write(file_content) end else # override source text of gem yaml_path = File.join(TranslationIO.config.yaml_locales_path, "#{@source_locale}.yml") if File.exists?(yaml_path) # source yaml file yaml_hash = YAML::load(File.read(yaml_path)) flat_yaml_hash = FlatHash.to_flat_hash(yaml_hash) else FileUtils::mkdir_p File.dirname(yaml_path) flat_yaml_hash = {} @yaml_file_paths = [yaml_path] + @yaml_file_paths end flat_yaml_hash["#{@source_locale}.#{source_edit['key']}"] = source_edit['new_text'] file_content = to_hash_to_yaml(flat_yaml_hash) File.open(yaml_path, 'w') do |f| f.write(file_content) end end inserted = true break else TranslationIO.info "#{source_edit['key']} | Ignored because translation was also updated in source YAML file", 2, 2 end end end break if inserted end end end File.open(TranslationIO.config.metadata_path, 'w') do |f| f.write({ 'timestamp' => Time.now.utc.to_i }.to_yaml) end end private def to_hash_to_yaml(flat_yaml_hash) yaml_hash = FlatHash.to_hash(flat_yaml_hash) if TranslationIO.config.yaml_line_width content = yaml_hash.to_yaml(:line_width => TranslationIO.config.yaml_line_width) else content = yaml_hash.to_yaml end content.gsub(/ $/, '') # remove trailing spaces end def metadata_timestamp if File.exist?(TranslationIO.config.metadata_path) metadata_content = File.read(TranslationIO.config.metadata_path) if metadata_content.include?('>>>>') || metadata_content.include?('<<<<') TranslationIO.info "[Error] #{TranslationIO.config.metadata_path} file is corrupted and seems to have unresolved versioning conflicts. Please resolve them and try again." exit(false) else return YAML::load(metadata_content)['timestamp'] rescue 0 end else return 0 end end def perform_source_edits_request(params) uri = URI("#{TranslationIO.client.endpoint}/projects/#{TranslationIO.client.api_key}/source_edits") parsed_response = BaseOperation.perform_request(uri, params) end # Sort YAML file paths by project locales first, gem locales after # (to replace "overridden" source first) def sort_by_project_locales_first(yaml_file_paths) yaml_file_paths.sort do |x, y| a = locale_file_path_in_project?(x) b = locale_file_path_in_project?(y) (!a && b) ? 1 : ((a && !b) ? -1 : 0) end end def locale_file_path_in_project?(locale_file_path) TranslationIO.normalize_path(locale_file_path).start_with?( TranslationIO.normalize_path(TranslationIO.config.yaml_locales_path) ) end end end end end Fix "preload yaml #35" and refactor ApplyYamlSourceEditsStep service module TranslationIO class Client class SyncOperation < BaseOperation class ApplyYamlSourceEditsStep def initialize(yaml_file_paths, source_locale) @yaml_file_paths = yaml_file_paths @source_locale = source_locale end def run(params) TranslationIO.info "Downloading YAML source editions." params.merge!({ :timestamp => metadata_timestamp }) parsed_response = perform_source_edits_request(params) source_edits = parsed_response['source_edits'].to_a TranslationIO.info "Applying YAML source editions." source_edits.each do |source_edit| inserted = false reload_or_reuse_yaml_sources @yaml_sources.each do |yaml_source| yaml_file_path = yaml_source[:yaml_file_path] yaml_flat_hash = yaml_source[:yaml_flat_hash] yaml_flat_hash.each do |full_key, value| if full_key == "#{@source_locale}.#{source_edit['key']}" inserted = apply_source_edit(source_edit, yaml_file_path, yaml_flat_hash) break if inserted end end break if inserted end end update_metadata_timestamp end private def reload_or_reuse_yaml_sources if yaml_sources_reload_needed? @yaml_sources = sort_by_project_locales_first(@yaml_file_paths).collect do |yaml_file_path| yaml_content = File.read(yaml_file_path) yaml_hash = YAML::load(yaml_content) yaml_flat_hash = FlatHash.to_flat_hash(yaml_hash) { :yaml_file_path => yaml_file_path, :yaml_flat_hash => yaml_flat_hash } end else @yaml_sources end end def yaml_sources_reload_needed? @yaml_file_paths.sort != @yaml_sources.to_a.collect { |y_s| y_s[:yaml_file_path] }.sort end # Sort YAML file paths by project locales first, gem locales after # (to replace "overridden" source first) def sort_by_project_locales_first(yaml_file_paths) yaml_file_paths.sort do |x, y| a = locale_file_path_in_project?(x) b = locale_file_path_in_project?(y) (!a && b) ? 1 : ((a && !b) ? -1 : 0) end end def apply_source_edit(source_edit, yaml_file_path, yaml_flat_hash) full_key = "#{@source_locale}.#{source_edit['key']}" if yaml_flat_hash[full_key] == source_edit['old_text'] TranslationIO.info "#{source_edit['key']} | #{source_edit['old_text']} -> #{source_edit['new_text']}", 2, 2 if locale_file_path_in_project?(yaml_file_path) apply_application_source_edit(source_edit, yaml_file_path, yaml_flat_hash) else # override source text of gem inside the app apply_gem_source_edit(source_edit) end return true else TranslationIO.info "#{source_edit['key']} | Ignored because translation was also updated in source YAML file", 2, 2 return false end end def apply_application_source_edit(source_edit, yaml_file_path, yaml_flat_hash) full_key = "#{@source_locale}.#{source_edit['key']}" yaml_flat_hash[full_key] = source_edit['new_text'] file_content = to_hash_to_yaml(yaml_flat_hash) File.open(yaml_file_path, 'w') do |f| f.write(file_content) end end def apply_gem_source_edit(source_edit) yaml_file_path = File.join(TranslationIO.config.yaml_locales_path, "#{@source_locale}.yml") if File.exists?(yaml_file_path) # source yaml file existing_yaml_source = @yaml_sources.detect { |y_s| y_s[:yaml_file_path] == yaml_file_path } yaml_flat_hash = existing_yaml_source[:yaml_flat_hash] else FileUtils::mkdir_p File.dirname(yaml_file_path) yaml_flat_hash = {} @yaml_file_paths = [yaml_file_path] + @yaml_file_paths end apply_application_source_edit(source_edit, yaml_file_path, yaml_flat_hash) end def to_hash_to_yaml(yaml_flat_hash) yaml_hash = FlatHash.to_hash(yaml_flat_hash) if TranslationIO.config.yaml_line_width content = yaml_hash.to_yaml(:line_width => TranslationIO.config.yaml_line_width) else content = yaml_hash.to_yaml end content.gsub(/ $/, '') # remove trailing spaces end def metadata_timestamp if File.exist?(TranslationIO.config.metadata_path) metadata_content = File.read(TranslationIO.config.metadata_path) if metadata_content.include?('>>>>') || metadata_content.include?('<<<<') TranslationIO.info "[Error] #{TranslationIO.config.metadata_path} file is corrupted and seems to have unresolved versioning conflicts. Please resolve them and try again." exit(false) else return YAML::load(metadata_content)['timestamp'] rescue 0 end else return 0 end end def update_metadata_timestamp File.open(TranslationIO.config.metadata_path, 'w') do |f| f.write({ 'timestamp' => Time.now.utc.to_i }.to_yaml) end end def perform_source_edits_request(params) uri = URI("#{TranslationIO.client.endpoint}/projects/#{TranslationIO.client.api_key}/source_edits") parsed_response = BaseOperation.perform_request(uri, params) end def locale_file_path_in_project?(locale_file_path) TranslationIO.normalize_path(locale_file_path).start_with?( TranslationIO.normalize_path(TranslationIO.config.yaml_locales_path) ) end end end end end
require 'vcloud' module Vcloud module EdgeGateway module ConfigurationGenerator class LoadBalancerService def initialize edge_gateway @edge_gateway = Vcloud::Core::EdgeGateway.get_by_name(edge_gateway) end def generate_fog_config(input_config) return nil if input_config.nil? out = {} out[:IsEnabled] = input_config.key?(:enabled) ? input_config[:enabled].to_s : 'true' out_pools = [] out_vs = [] if pools = input_config[:pools] pools.each do |pool| out_pools << generate_pool_entry(pool) end end if vses = input_config[:virtual_servers] vses.each do |vs| out_vs << generate_virtual_server_entry(vs) end end out[:Pool] = out_pools out[:VirtualServer] = out_vs out end private def generate_virtual_server_entry(attrs) out = {} out[:IsEnabled] = attrs.key(:enabled) ? attrs[:enabled] : 'true' out[:Name] = attrs[:name] out[:Description] = attrs[:description] || '' out[:Interface] = generate_vs_interface_section(attrs[:network]) out[:IpAddress] = attrs[:ip_address] out[:ServiceProfile] = generate_vs_service_profile_section(attrs[:service_profiles]) out[:Logging] = attrs.key(:logging) ? attrs[:logging] : 'false' out[:Pool] = attrs[:pool] out end def generate_vs_interface_section(network_id) out = {} out[:type] = 'application/vnd.vmware.vcloud.orgVdcNetwork+xml' out[:name] = look_up_network_name(network_id) out[:href] = look_up_network_href(network_id) out end def look_up_network_name(network_id) gateway_interface = @edge_gateway.vcloud_gateway_interface_by_id(network_id) raise "Could not find network #{network_id}" unless gateway_interface gateway_interface[:Network][:name] end def look_up_network_href(network_id) gateway_interface = @edge_gateway.vcloud_gateway_interface_by_id(network_id) raise "Could not find network #{network_id}" unless gateway_interface gateway_interface[:Network][:href] end def generate_vs_service_profile_section(attrs) attrs = {} if attrs.nil? out = [] protocols = [ :http, :https, :tcp ] protocols.each do |protocol| out << generate_vs_service_profile_protocol_section(protocol, attrs[protocol]) end out end def generate_vs_service_profile_protocol_section(protocol, attrs) out = { IsEnabled: 'false', Protocol: protocol.to_s.upcase, Port: default_port(protocol), Persistence: generate_vs_persistence_section(protocol, nil) } if attrs out[:IsEnabled] = attrs.key?(:enabled) ? attrs[:enabled].to_s : 'true' out[:Port] = attrs.key?(:port) ? attrs[:port].to_s : default_port(protocol) out[:Persistence] = generate_vs_persistence_section(protocol, attrs[:persistence]) end out end def default_port(protocol) dp = { http: '80', https: '443', tcp: '' } dp[protocol] end def generate_vs_persistence_section(protocol, attrs) attrs = {} if attrs.nil? out = { Method: '' } out[:Method] = attrs[:method] if attrs.key?(:method) out end def generate_pool_entry(attrs) sp_modes = [ :http, :https, :tcp ] out = {} out[:Name] = attrs[:name] out[:Description] = attrs[:description] if attrs.key?(:description) out[:ServicePort] = sp_modes.map do |mode| generate_pool_service_port(mode, attrs.key?(:service) ? attrs[:service][mode] : nil) end if attrs.key?(:members) out[:Member] = [] attrs[:members].each do |member| out[:Member] << generate_pool_member_entry(member) end end out end def generate_pool_member_entry(attrs) { IpAddress: attrs[:ip_address], Weight: attrs[:weight] || '1', ServicePort: [ { Protocol: 'HTTP', Port: '', HealthCheckPort: '' }, { Protocol: 'HTTPS', Port: '', HealthCheckPort: '' }, { Protocol: 'TCP', Port: '', HealthCheckPort: '' }, ] } end def generate_pool_service_port(mode, attrs) out = { IsEnabled: 'false', Protocol: mode.to_s.upcase, Algorithm: 'ROUND_ROBIN', Port: default_port(mode), HealthCheckPort: '', HealthCheck: generate_pool_healthcheck(mode) } if attrs out[:IsEnabled] = attrs.key?(:enabled) ? attrs[:enabled].to_s : 'true' out[:Algorithm] = attrs[:algorithm] if attrs.key?(:algorithm) out[:Port] = attrs.key?(:port) ? attrs[:port].to_s : default_port(mode) if health_check = attrs[:health_check] out[:HealthCheckPort] = health_check.key?(:port) ? health_check[:port] : '' out[:HealthCheck] = generate_pool_healthcheck(mode, attrs[:health_check]) end end out end def generate_pool_healthcheck(protocol, attrs = nil) default_mode = ( protocol == :https ) ? 'SSL' : protocol.to_s.upcase out = { Mode: default_mode, } out[:Uri] = '' if protocol == :http out[:HealthThreshold] = '2' out[:UnhealthThreshold] = '3' out[:Interval] = '5' out[:Timeout] = '15' if attrs out[:Mode] = attrs[:protocol] if attrs.key?(:protocol) out[:Uri] = attrs[:uri] if attrs.key?(:uri) and protocol == :http out[:HealthThreshold] = attrs[:health_threshold] if attrs.key?(:health_threshold) out[:UnhealthThreshold] = attrs[:unhealth_threshold] if attrs.key?(:unhealth_threshold) out[:Interval] = attrs[:interval] if attrs.key?(:interval) out[:Timeout] = attrs[:timeout] if attrs.key?(:timeout) end out end end end end end LoadBalancer pool weight fix Pool weight should be a string, despite being specified as an integer. require 'vcloud' module Vcloud module EdgeGateway module ConfigurationGenerator class LoadBalancerService def initialize edge_gateway @edge_gateway = Vcloud::Core::EdgeGateway.get_by_name(edge_gateway) end def generate_fog_config(input_config) return nil if input_config.nil? out = {} out[:IsEnabled] = input_config.key?(:enabled) ? input_config[:enabled].to_s : 'true' out_pools = [] out_vs = [] if pools = input_config[:pools] pools.each do |pool| out_pools << generate_pool_entry(pool) end end if vses = input_config[:virtual_servers] vses.each do |vs| out_vs << generate_virtual_server_entry(vs) end end out[:Pool] = out_pools out[:VirtualServer] = out_vs out end private def generate_virtual_server_entry(attrs) out = {} out[:IsEnabled] = attrs.key(:enabled) ? attrs[:enabled] : 'true' out[:Name] = attrs[:name] out[:Description] = attrs[:description] || '' out[:Interface] = generate_vs_interface_section(attrs[:network]) out[:IpAddress] = attrs[:ip_address] out[:ServiceProfile] = generate_vs_service_profile_section(attrs[:service_profiles]) out[:Logging] = attrs.key(:logging) ? attrs[:logging] : 'false' out[:Pool] = attrs[:pool] out end def generate_vs_interface_section(network_id) out = {} out[:type] = 'application/vnd.vmware.vcloud.orgVdcNetwork+xml' out[:name] = look_up_network_name(network_id) out[:href] = look_up_network_href(network_id) out end def look_up_network_name(network_id) gateway_interface = @edge_gateway.vcloud_gateway_interface_by_id(network_id) raise "Could not find network #{network_id}" unless gateway_interface gateway_interface[:Network][:name] end def look_up_network_href(network_id) gateway_interface = @edge_gateway.vcloud_gateway_interface_by_id(network_id) raise "Could not find network #{network_id}" unless gateway_interface gateway_interface[:Network][:href] end def generate_vs_service_profile_section(attrs) attrs = {} if attrs.nil? out = [] protocols = [ :http, :https, :tcp ] protocols.each do |protocol| out << generate_vs_service_profile_protocol_section(protocol, attrs[protocol]) end out end def generate_vs_service_profile_protocol_section(protocol, attrs) out = { IsEnabled: 'false', Protocol: protocol.to_s.upcase, Port: default_port(protocol), Persistence: generate_vs_persistence_section(protocol, nil) } if attrs out[:IsEnabled] = attrs.key?(:enabled) ? attrs[:enabled].to_s : 'true' out[:Port] = attrs.key?(:port) ? attrs[:port].to_s : default_port(protocol) out[:Persistence] = generate_vs_persistence_section(protocol, attrs[:persistence]) end out end def default_port(protocol) dp = { http: '80', https: '443', tcp: '' } dp[protocol] end def generate_vs_persistence_section(protocol, attrs) attrs = {} if attrs.nil? out = { Method: '' } out[:Method] = attrs[:method] if attrs.key?(:method) out end def generate_pool_entry(attrs) sp_modes = [ :http, :https, :tcp ] out = {} out[:Name] = attrs[:name] out[:Description] = attrs[:description] if attrs.key?(:description) out[:ServicePort] = sp_modes.map do |mode| generate_pool_service_port(mode, attrs.key?(:service) ? attrs[:service][mode] : nil) end if attrs.key?(:members) out[:Member] = [] attrs[:members].each do |member| out[:Member] << generate_pool_member_entry(member) end end out end def generate_pool_member_entry(attrs) { IpAddress: attrs[:ip_address], Weight: attrs.key?(:weight) ? attrs[:weight].to_s : '1', ServicePort: [ { Protocol: 'HTTP', Port: '', HealthCheckPort: '' }, { Protocol: 'HTTPS', Port: '', HealthCheckPort: '' }, { Protocol: 'TCP', Port: '', HealthCheckPort: '' }, ] } end def generate_pool_service_port(mode, attrs) out = { IsEnabled: 'false', Protocol: mode.to_s.upcase, Algorithm: 'ROUND_ROBIN', Port: default_port(mode), HealthCheckPort: '', HealthCheck: generate_pool_healthcheck(mode) } if attrs out[:IsEnabled] = attrs.key?(:enabled) ? attrs[:enabled].to_s : 'true' out[:Algorithm] = attrs[:algorithm] if attrs.key?(:algorithm) out[:Port] = attrs.key?(:port) ? attrs[:port].to_s : default_port(mode) if health_check = attrs[:health_check] out[:HealthCheckPort] = health_check.key?(:port) ? health_check[:port] : '' out[:HealthCheck] = generate_pool_healthcheck(mode, attrs[:health_check]) end end out end def generate_pool_healthcheck(protocol, attrs = nil) default_mode = ( protocol == :https ) ? 'SSL' : protocol.to_s.upcase out = { Mode: default_mode, } out[:Uri] = '' if protocol == :http out[:HealthThreshold] = '2' out[:UnhealthThreshold] = '3' out[:Interval] = '5' out[:Timeout] = '15' if attrs out[:Mode] = attrs[:protocol] if attrs.key?(:protocol) out[:Uri] = attrs[:uri] if attrs.key?(:uri) and protocol == :http out[:HealthThreshold] = attrs[:health_threshold] if attrs.key?(:health_threshold) out[:UnhealthThreshold] = attrs[:unhealth_threshold] if attrs.key?(:unhealth_threshold) out[:Interval] = attrs[:interval] if attrs.key?(:interval) out[:Timeout] = attrs[:timeout] if attrs.key?(:timeout) end out end end end end end
def round_up(value, increment) increment * ((value + increment - 1) / increment) end RSpec.shared_examples "evenly distributable" do |group_name| it "by ensuring instance count is a multiple of AZ count" do expect(group_name).not_to be_nil ig = subject.fetch("instance_groups." + group_name) az_count = ig.fetch("azs").size instance_count = ig.fetch("instances") expect(instance_count % az_count).to eq(0), group_name + " instance count (#{instance_count}) is not divisible by AZ count (#{az_count})" end end RSpec.describe "Instance counts in different environments" do %w[prod prod-lon stg-lon].each do |env| context "for the #{env} environment" do subject { manifest_for_env(env) } let(:env_manifest) { manifest_for_env(env) } describe "cells" do it_behaves_like("evenly distributable", "diego-cell") end describe "doppler" do it_behaves_like("evenly distributable", "doppler") it "instance count should be at least half of the cell count" do doppler_ig = env_manifest.fetch("instance_groups.doppler") cell_instance_count = env_manifest.fetch("instance_groups.diego-cell").dig("instances").to_f doppler_instance_count = doppler_ig.dig("instances").to_f doppler_az_count = doppler_ig.fetch("azs").size half = cell_instance_count / 2 half_with_headroom = round_up(half, doppler_az_count) + doppler_az_count expect(doppler_instance_count).to be >= half, "doppler instance count #{doppler_instance_count} is wrong. Rule of thumb is there should be at least half the count of cells in dopplers. Currently set to #{doppler_instance_count}, expecting at least #{half}." expect(doppler_instance_count).to be <= half_with_headroom, "doppler instance count #{doppler_instance_count} is too high. There is no need to allow more headroom than a single set of #{doppler_az_count}. Currently set to #{doppler_instance_count}, expecting at least #{half_with_headroom}." end end describe "log-api" do it_behaves_like("evenly distributable", "log-api") it "instance count should be at least half of the doppler count" do log_api_ig = env_manifest.fetch("instance_groups.log-api") doppler_instance_count = env_manifest.fetch("instance_groups.doppler").dig("instances").to_f log_api_instances_count = log_api_ig.dig("instances").to_f log_api_az_count = log_api_ig.fetch("azs").size half = doppler_instance_count / 2 half_with_headroom = round_up(half, log_api_az_count) + log_api_az_count expect(log_api_instances_count).to be >= half, "log-api instance count #{log_api_instances_count} is wrong. Rule of thumb is there should be at least half the count of dopplers in log-api. Currently set to #{log_api_instances_count}, expecting at least #{half}." expect(log_api_instances_count).to be <= half_with_headroom, "log-api instance count #{log_api_instances_count} is too high. There is no need to allow more headroom than a single set of three. Currently set to #{log_api_instances_count}, expecting at least #{half_with_headroom}." end end describe "cc-worker" do it_behaves_like("evenly distributable", "cc-worker") it "instance count should be at least half of the API instance count" do cc_worker_ig = env_manifest.fetch("instance_groups.cc-worker") api_instance_count = env_manifest.fetch("instance_groups.api").dig("instances").to_f cc_worker_instances_count = cc_worker_ig.dig("instances").to_f cc_worker_az_count = cc_worker_ig.fetch("azs").size half = api_instance_count / 2 half_with_headroom = round_up(half, cc_worker_az_count) + cc_worker_az_count expect(cc_worker_instances_count).to be >= half, "cc-worker instance count #{cc_worker_instances_count} is wrong. Rule of thumb is there should be at least half the count of api in cc-workers. Currently set to #{cc_worker_instances_count}, expecting at least #{half}." expect(cc_worker_instances_count).to be <= half_with_headroom, "cc-worker instance count #{cc_worker_instances_count} is too high. There is no need to allow more headroom than a single set of #{cc_worker_az_count}. Currently set to #{cc_worker_instances_count}, expecting at least #{half_with_headroom}." end end describe "scheduler" do it "instance count should be at least half of the API instance count" do scheduler_ig = env_manifest.fetch("instance_groups.scheduler") api_instance_count = env_manifest.fetch("instance_groups.api").dig("instances").to_f scheduler_instances_count = scheduler_ig.dig("instances").to_f scheduler_az_count = scheduler_ig.fetch("azs").size half = api_instance_count / 2 half_with_headroom = round_up(half, scheduler_az_count) + scheduler_az_count expect(scheduler_instances_count).to be >= half, "scheduler instance count #{scheduler_instances_count} is wrong. Rule of thumb is there should be at least half the count of api in schedulers. Currently set to #{scheduler_instances_count}, expecting at least #{half}." expect(scheduler_instances_count).to be <= half_with_headroom, "log-api instance count #{scheduler_instances_count} is too high. There is no need to allow more headroom than a single set of #{scheduler_az_count}. Currently set to #{scheduler_instances_count}, expecting at least #{half_with_headroom}." end end end end end Comment out high infra instance count check This test does not take into account diego-cells in isolation segments. We need to scale Notify isolation segments for load-testing in anticipation of higher utilisation and not bottleneck on the infra level. def round_up(value, increment) increment * ((value + increment - 1) / increment) end RSpec.shared_examples "evenly distributable" do |group_name| it "by ensuring instance count is a multiple of AZ count" do expect(group_name).not_to be_nil ig = subject.fetch("instance_groups." + group_name) az_count = ig.fetch("azs").size instance_count = ig.fetch("instances") expect(instance_count % az_count).to eq(0), group_name + " instance count (#{instance_count}) is not divisible by AZ count (#{az_count})" end end RSpec.describe "Instance counts in different environments" do %w[prod prod-lon stg-lon].each do |env| context "for the #{env} environment" do subject { manifest_for_env(env) } let(:env_manifest) { manifest_for_env(env) } describe "cells" do it_behaves_like("evenly distributable", "diego-cell") end describe "doppler" do it_behaves_like("evenly distributable", "doppler") it "instance count should be at least half of the cell count" do doppler_ig = env_manifest.fetch("instance_groups.doppler") cell_instance_count = env_manifest.fetch("instance_groups.diego-cell").dig("instances").to_f doppler_instance_count = doppler_ig.dig("instances").to_f doppler_az_count = doppler_ig.fetch("azs").size half = cell_instance_count / 2 half_with_headroom = round_up(half, doppler_az_count) + doppler_az_count expect(doppler_instance_count).to be >= half, "doppler instance count #{doppler_instance_count} is wrong. Rule of thumb is there should be at least half the count of cells in dopplers. Currently set to #{doppler_instance_count}, expecting at least #{half}." expect(doppler_instance_count).to be <= half_with_headroom, "doppler instance count #{doppler_instance_count} is too high. There is no need to allow more headroom than a single set of #{doppler_az_count}. Currently set to #{doppler_instance_count}, expecting at least #{half_with_headroom}." end end describe "log-api" do it_behaves_like("evenly distributable", "log-api") it "instance count should be at least half of the doppler count" do log_api_ig = env_manifest.fetch("instance_groups.log-api") doppler_instance_count = env_manifest.fetch("instance_groups.doppler").dig("instances").to_f log_api_instances_count = log_api_ig.dig("instances").to_f log_api_az_count = log_api_ig.fetch("azs").size half = doppler_instance_count / 2 half_with_headroom = round_up(half, log_api_az_count) + log_api_az_count expect(log_api_instances_count).to be >= half, "log-api instance count #{log_api_instances_count} is wrong. Rule of thumb is there should be at least half the count of dopplers in log-api. Currently set to #{log_api_instances_count}, expecting at least #{half}." expect(log_api_instances_count).to be <= half_with_headroom, "log-api instance count #{log_api_instances_count} is too high. There is no need to allow more headroom than a single set of three. Currently set to #{log_api_instances_count}, expecting at least #{half_with_headroom}." end end describe "cc-worker" do it_behaves_like("evenly distributable", "cc-worker") it "instance count should be at least half of the API instance count" do cc_worker_ig = env_manifest.fetch("instance_groups.cc-worker") api_instance_count = env_manifest.fetch("instance_groups.api").dig("instances").to_f cc_worker_instances_count = cc_worker_ig.dig("instances").to_f # Comment out check for overreaching instance count for now: # This check does not consider cells in isolation segments # cc_worker_az_count = cc_worker_ig.fetch("azs").size half = api_instance_count / 2 # half_with_headroom = round_up(half, cc_worker_az_count) + cc_worker_az_count expect(cc_worker_instances_count).to be >= half, "cc-worker instance count #{cc_worker_instances_count} is wrong. Rule of thumb is there should be at least half the count of api in cc-workers. Currently set to #{cc_worker_instances_count}, expecting at least #{half}." # expect(cc_worker_instances_count).to be <= half_with_headroom, "cc-worker instance count #{cc_worker_instances_count} is too high. There is no need to allow more headroom than a single set of #{cc_worker_az_count}. Currently set to #{cc_worker_instances_count}, expecting at least #{half_with_headroom}." end end describe "scheduler" do it "instance count should be at least half of the API instance count" do scheduler_ig = env_manifest.fetch("instance_groups.scheduler") api_instance_count = env_manifest.fetch("instance_groups.api").dig("instances").to_f scheduler_instances_count = scheduler_ig.dig("instances").to_f scheduler_az_count = scheduler_ig.fetch("azs").size half = api_instance_count / 2 half_with_headroom = round_up(half, scheduler_az_count) + scheduler_az_count expect(scheduler_instances_count).to be >= half, "scheduler instance count #{scheduler_instances_count} is wrong. Rule of thumb is there should be at least half the count of api in schedulers. Currently set to #{scheduler_instances_count}, expecting at least #{half}." expect(scheduler_instances_count).to be <= half_with_headroom, "log-api instance count #{scheduler_instances_count} is too high. There is no need to allow more headroom than a single set of #{scheduler_az_count}. Currently set to #{scheduler_instances_count}, expecting at least #{half_with_headroom}." end end end end end
module PipelineOptions def run_post_registration_hooks(m, job, params) return unless authorized?(m) messages = [] if params[:pipeline] pipeline = params[:pipeline] messages << "pipeline: /#{pipeline}/" end phantomjs_triggers = [ :phantomjs, :phantomjs_scroll, :phantomjs_wait, :no_phantomjs_smart_scroll ] if phantomjs_triggers.any? { |t| params[t] } job.use_phantomjs(params[:phantomjs_scroll], params[:phantomjs_wait], params[:no_phantomjs_smart_scroll]) messages << "phantomjs: yes, #{job.phantomjs_info}" end if params[:youtube_dl] job.use_youtube_dl messages << 'youtube-dl: yes' end if params[:no_offsite_links] job.no_offsite_links! messages << 'offsite links: no' end if !messages.empty? reply m, "Options: #{messages.join('; ')}" end super end end bot: Link to "youtube-dl is totes experimental" blurb. module PipelineOptions def run_post_registration_hooks(m, job, params) return unless authorized?(m) messages = [] if params[:pipeline] pipeline = params[:pipeline] messages << "pipeline: /#{pipeline}/" end phantomjs_triggers = [ :phantomjs, :phantomjs_scroll, :phantomjs_wait, :no_phantomjs_smart_scroll ] if phantomjs_triggers.any? { |t| params[t] } job.use_phantomjs(params[:phantomjs_scroll], params[:phantomjs_wait], params[:no_phantomjs_smart_scroll]) messages << "phantomjs: yes, #{job.phantomjs_info}" end if params[:youtube_dl] job.use_youtube_dl messages << 'youtube-dl: yes (please read https://git.io/vUjC0)' end if params[:no_offsite_links] job.no_offsite_links! messages << 'offsite links: no' end if !messages.empty? reply m, "Options: #{messages.join('; ')}" end super end end
# encoding: UTF-8 Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'spree_auth_devise' s.version = '2.2.0' s.summary = 'Provides authentication and authorization services for use with Spree by using Devise and CanCan.' s.description = s.summary s.required_ruby_version = '>= 1.9.3' s.author = 'Sean Schofield' s.email = 'sean@spreecommerce.com' s.homepage = 'http://spreecommerce.com' s.license = %q{BSD-3} s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- spec/*`.split("\n") s.require_path = 'lib' s.requirements << 'none' spree_version = '~> 2.3.0.beta' s.add_dependency 'spree_core', spree_version s.add_dependency 'devise', '~> 3.2.3' s.add_dependency 'devise-encryptable', '0.1.2' s.add_dependency 'cancan', '~> 1.6.10' s.add_dependency 'json' s.add_dependency 'multi_json' s.add_development_dependency 'spree_backend', spree_version s.add_development_dependency 'spree_frontend', spree_version s.add_development_dependency 'sqlite3' s.add_development_dependency 'mysql2' s.add_development_dependency 'pg' s.add_development_dependency 'sass-rails', '~> 4.0.0' s.add_development_dependency 'coffee-rails', '~> 4.0.0' s.add_development_dependency 'rspec-rails', '~> 2.14' s.add_development_dependency 'factory_girl', '~> 4.4' s.add_development_dependency 'email_spec', '~> 1.5.0' s.add_development_dependency 'ffaker' s.add_development_dependency 'shoulda-matchers', '~> 1.5' s.add_development_dependency 'capybara', '~> 2.2.1' s.add_development_dependency 'database_cleaner', '~> 1.2.0' s.add_development_dependency 'selenium-webdriver' s.add_development_dependency 'poltergeist', '~> 1.5.0' s.add_development_dependency 'launchy' s.add_development_dependency 'simplecov', '~> 0.7.1' s.add_development_dependency 'pry' end Use Spree 2.3.0 # encoding: UTF-8 Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'spree_auth_devise' s.version = '2.2.0' s.summary = 'Provides authentication and authorization services for use with Spree by using Devise and CanCan.' s.description = s.summary s.required_ruby_version = '>= 1.9.3' s.author = 'Sean Schofield' s.email = 'sean@spreecommerce.com' s.homepage = 'http://spreecommerce.com' s.license = %q{BSD-3} s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- spec/*`.split("\n") s.require_path = 'lib' s.requirements << 'none' spree_version = '~> 2.3.0' s.add_dependency 'spree_core', spree_version s.add_dependency 'devise', '~> 3.2.3' s.add_dependency 'devise-encryptable', '0.1.2' s.add_dependency 'cancan', '~> 1.6.10' s.add_dependency 'json' s.add_dependency 'multi_json' s.add_development_dependency 'spree_backend', spree_version s.add_development_dependency 'spree_frontend', spree_version s.add_development_dependency 'sqlite3' s.add_development_dependency 'mysql2' s.add_development_dependency 'pg' s.add_development_dependency 'sass-rails', '~> 4.0.0' s.add_development_dependency 'coffee-rails', '~> 4.0.0' s.add_development_dependency 'rspec-rails', '~> 2.14' s.add_development_dependency 'factory_girl', '~> 4.4' s.add_development_dependency 'email_spec', '~> 1.5.0' s.add_development_dependency 'ffaker' s.add_development_dependency 'shoulda-matchers', '~> 1.5' s.add_development_dependency 'capybara', '~> 2.2.1' s.add_development_dependency 'database_cleaner', '~> 1.2.0' s.add_development_dependency 'selenium-webdriver' s.add_development_dependency 'poltergeist', '~> 1.5.0' s.add_development_dependency 'launchy' s.add_development_dependency 'simplecov', '~> 0.7.1' s.add_development_dependency 'pry' end
module ActiveForm class FormDefinition attr_accessor :assoc_name, :proc, :parent, :records def initialize(args={}) assign_arguments(args) end def to_form if !association_reflection return nil end macro = association_reflection.macro case macro when :has_one Form.new(assoc_name, parent, proc) when :has_many FormCollection.new(assoc_name, parent, proc, {records: records}) end end private def assign_arguments(args={}) args.each do |key, value| send("#{key}=", value) if respond_to?(key) end end def association_reflection parent.class.reflect_on_association(@assoc_name) end end end Update The FormDefinition#to_form method to handle also the case for a belongs_to association. module ActiveForm class FormDefinition attr_accessor :assoc_name, :proc, :parent, :records def initialize(args={}) assign_arguments(args) end def to_form if !association_reflection return nil end macro = association_reflection.macro case macro when :belongs_to Form.new(assoc_name, parent, proc) when :has_one Form.new(assoc_name, parent, proc) when :has_many FormCollection.new(assoc_name, parent, proc, {records: records}) end end private def assign_arguments(args={}) args.each do |key, value| send("#{key}=", value) if respond_to?(key) end end def association_reflection parent.class.reflect_on_association(@assoc_name) end end end
module Addic7edDownloader VERSION = '1.0.6'.freeze end Version bump module Addic7edDownloader VERSION = '1.0.7'.freeze end
module ArtirixDataModels VERSION = '0.32.0' end version 1.0 beta1 module ArtirixDataModels VERSION = '1.0.0.beta1' end
# encoding: UTF-8 module Asciidoctor # A built-in {Converter} implementation that generates HTML 5 output # consistent with the html5 backend from AsciiDoc Python. class Converter::Html5Converter < Converter::BuiltIn QUOTE_TAGS = { :emphasis => ['<em>', '</em>', true], :strong => ['<strong>', '</strong>', true], :monospaced => ['<code>', '</code>', true], :superscript => ['<sup>', '</sup>', true], :subscript => ['<sub>', '</sub>', true], :double => ['&#8220;', '&#8221;', false], :single => ['&#8216;', '&#8217;', false], :mark => ['<mark>', '</mark>', true], :asciimath => ['\\$', '\\$', false], :latexmath => ['\\(', '\\)', false] # Opal can't resolve these constants when referenced here #:asciimath => INLINE_MATH_DELIMITERS[:asciimath] + [false], #:latexmath => INLINE_MATH_DELIMITERS[:latexmath] + [false] } QUOTE_TAGS.default = [nil, nil, nil] def initialize backend, opts = {} @xml_mode = opts[:htmlsyntax] == 'xml' @void_element_slash = @xml_mode ? '/' : nil @stylesheets = Stylesheets.instance end def document node result = [] slash = @void_element_slash br = %(<br#{slash}>) unless (asset_uri_scheme = (node.attr 'asset-uri-scheme', 'https')).empty? asset_uri_scheme = %(#{asset_uri_scheme}:) end cdn_base = %(#{asset_uri_scheme}//cdnjs.cloudflare.com/ajax/libs) linkcss = node.safe >= SafeMode::SECURE || (node.attr? 'linkcss') result << '<!DOCTYPE html>' lang_attribute = (node.attr? 'nolang') ? nil : %( lang="#{node.attr 'lang', 'en'}") result << %(<html#{@xml_mode ? ' xmlns="http://www.w3.org/1999/xhtml"' : nil}#{lang_attribute}>) result << %(<head> <meta charset="#{node.attr 'encoding', 'UTF-8'}"#{slash}> <!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"#{slash}><![endif]--> <meta name="viewport" content="width=device-width, initial-scale=1.0"#{slash}> <meta name="generator" content="Asciidoctor #{node.attr 'asciidoctor-version'}"#{slash}>) result << %(<meta name="application-name" content="#{node.attr 'app-name'}"#{slash}>) if node.attr? 'app-name' result << %(<meta name="description" content="#{node.attr 'description'}"#{slash}>) if node.attr? 'description' result << %(<meta name="keywords" content="#{node.attr 'keywords'}"#{slash}>) if node.attr? 'keywords' result << %(<meta name="author" content="#{node.attr 'authors'}"#{slash}>) if node.attr? 'authors' result << %(<meta name="copyright" content="#{node.attr 'copyright'}"#{slash}>) if node.attr? 'copyright' result << %(<title>#{node.doctitle :sanitize => true, :use_fallback => true}</title>) if DEFAULT_STYLESHEET_KEYS.include?(node.attr 'stylesheet') if (webfonts = node.attr 'webfonts') result << %(<link rel="stylesheet" href="#{asset_uri_scheme}//fonts.googleapis.com/css?family=#{webfonts.empty? ? 'Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700' : webfonts}"#{slash}>) end if linkcss result << %(<link rel="stylesheet" href="#{node.normalize_web_path DEFAULT_STYLESHEET_NAME, (node.attr 'stylesdir', ''), false}"#{slash}>) else result << @stylesheets.embed_primary_stylesheet end elsif node.attr? 'stylesheet' if linkcss result << %(<link rel="stylesheet" href="#{node.normalize_web_path((node.attr 'stylesheet'), (node.attr 'stylesdir', ''))}"#{slash}>) else result << %(<style> #{node.read_asset node.normalize_system_path((node.attr 'stylesheet'), (node.attr 'stylesdir', '')), :warn_on_failure => true} </style>) end end if node.attr? 'icons', 'font' if node.attr? 'iconfont-remote' result << %(<link rel="stylesheet" href="#{node.attr 'iconfont-cdn', %[#{cdn_base}/font-awesome/4.3.0/css/font-awesome.min.css]}"#{slash}>) else iconfont_stylesheet = %(#{node.attr 'iconfont-name', 'font-awesome'}.css) result << %(<link rel="stylesheet" href="#{node.normalize_web_path iconfont_stylesheet, (node.attr 'stylesdir', ''), false}"#{slash}>) end end case (highlighter = node.attr 'source-highlighter') when 'coderay' if (node.attr 'coderay-css', 'class') == 'class' if linkcss result << %(<link rel="stylesheet" href="#{node.normalize_web_path @stylesheets.coderay_stylesheet_name, (node.attr 'stylesdir', ''), false}"#{slash}>) else result << @stylesheets.embed_coderay_stylesheet end end when 'pygments' if (node.attr 'pygments-css', 'class') == 'class' pygments_style = node.attr 'pygments-style' if linkcss result << %(<link rel="stylesheet" href="#{node.normalize_web_path @stylesheets.pygments_stylesheet_name(pygments_style), (node.attr 'stylesdir', ''), false}"#{slash}>) else result << (@stylesheets.embed_pygments_stylesheet pygments_style) end end end unless (docinfo_content = node.docinfo).empty? result << docinfo_content end result << '</head>' body_attrs = [] if node.id body_attrs << %(id="#{node.id}") end if (node.attr? 'toc-class') && (node.attr? 'toc') && (node.attr? 'toc-placement', 'auto') body_attrs << %(class="#{node.doctype} #{node.attr 'toc-class'} toc-#{node.attr 'toc-position', 'header'}") else body_attrs << %(class="#{node.doctype}") end if node.attr? 'max-width' body_attrs << %(style="max-width: #{node.attr 'max-width'};") end result << %(<body #{body_attrs * ' '}>) unless node.noheader result << '<div id="header">' if node.doctype == 'manpage' result << %(<h1>#{node.doctitle} Manual Page</h1>) if (node.attr? 'toc') && (node.attr? 'toc-placement', 'auto') result << %(<div id="toc" class="#{node.attr 'toc-class', 'toc'}"> <div id="toctitle">#{node.attr 'toc-title'}</div> #{outline node} </div>) end result << %(<h2>#{node.attr 'manname-title'}</h2> <div class="sectionbody"> <p>#{node.attr 'manname'} - #{node.attr 'manpurpose'}</p> </div>) else if node.has_header? result << %(<h1>#{node.header.title}</h1>) unless node.notitle details = [] if node.attr? 'author' details << %(<span id="author" class="author">#{node.attr 'author'}</span>#{br}) if node.attr? 'email' details << %(<span id="email" class="email">#{node.sub_macros(node.attr 'email')}</span>#{br}) end if (authorcount = (node.attr 'authorcount').to_i) > 1 (2..authorcount).each do |idx| details << %(<span id="author#{idx}" class="author">#{node.attr "author_#{idx}"}</span>#{br}) if node.attr? %(email_#{idx}) details << %(<span id="email#{idx}" class="email">#{node.sub_macros(node.attr "email_#{idx}")}</span>#{br}) end end end end if node.attr? 'revnumber' details << %(<span id="revnumber">#{((node.attr 'version-label') || '').downcase} #{node.attr 'revnumber'}#{(node.attr? 'revdate') ? ',' : ''}</span>) end if node.attr? 'revdate' details << %(<span id="revdate">#{node.attr 'revdate'}</span>) end if node.attr? 'revremark' details << %(#{br}<span id="revremark">#{node.attr 'revremark'}</span>) end unless details.empty? result << '<div class="details">' result.concat details result << '</div>' end end if (node.attr? 'toc') && (node.attr? 'toc-placement', 'auto') result << %(<div id="toc" class="#{node.attr 'toc-class', 'toc'}"> <div id="toctitle">#{node.attr 'toc-title'}</div> #{outline node} </div>) end end result << '</div>' end result << %(<div id="content"> #{node.content} </div>) if node.footnotes? && !(node.attr? 'nofootnotes') result << %(<div id="footnotes"> <hr#{slash}>) node.footnotes.each do |footnote| result << %(<div class="footnote" id="_footnote_#{footnote.index}"> <a href="#_footnoteref_#{footnote.index}">#{footnote.index}</a>. #{footnote.text} </div>) end result << '</div>' end unless node.nofooter result << '<div id="footer">' result << '<div id="footer-text">' if node.attr? 'revnumber' result << %(#{node.attr 'version-label'} #{node.attr 'revnumber'}#{br}) end if node.attr? 'last-update-label' result << %(#{node.attr 'last-update-label'} #{node.attr 'docdatetime'}) end result << '</div>' unless (docinfo_content = node.docinfo :footer).empty? result << docinfo_content end result << '</div>' end # Load Javascript at the end of body for performance # See http://www.html5rocks.com/en/tutorials/speed/script-loading/ case highlighter when 'highlightjs', 'highlight.js' highlightjs_path = node.attr 'highlightjsdir', %(#{cdn_base}/highlight.js/8.6) result << %(<link rel="stylesheet" href="#{highlightjs_path}/styles/#{node.attr 'highlightjs-theme', 'github'}.min.css"#{slash}>) result << %(<script src="#{highlightjs_path}/highlight.min.js"></script> <script>hljs.initHighlighting()</script>) when 'prettify' prettify_path = node.attr 'prettifydir', %(#{cdn_base}/prettify/r298) result << %(<link rel="stylesheet" href="#{prettify_path}/#{node.attr 'prettify-theme', 'prettify'}.min.css"#{slash}>) result << %(<script src="#{prettify_path}/prettify.min.js"></script> <script>prettyPrint()</script>) end if node.attr? 'stem' # IMPORTANT to_s calls on delimiter arrays are intentional for JavaScript compat (emulates JSON.stringify) eqnums_val = node.attr 'eqnums', 'none' eqnums_val = 'AMS' if eqnums_val == '' eqnums_opt = %( equationNumbers: { autoNumber: "#{eqnums_val}" } ) result << %(<script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: { inlineMath: [#{INLINE_MATH_DELIMITERS[:latexmath].inspect}], displayMath: [#{BLOCK_MATH_DELIMITERS[:latexmath].inspect}], ignoreClass: "nostem|nolatexmath" }, asciimath2jax: { delimiters: [#{BLOCK_MATH_DELIMITERS[:asciimath].inspect}], ignoreClass: "nostem|noasciimath" }, TeX: {#{eqnums_opt}} }); </script> <script src="#{cdn_base}/mathjax/2.4.0/MathJax.js?config=TeX-MML-AM_HTMLorMML"></script>) end result << '</body>' result << '</html>' result * EOL end def embedded node result = [] if !node.notitle && node.has_header? id_attr = node.id ? %( id="#{node.id}") : nil result << %(<h1#{id_attr}>#{node.header.title}</h1>) end result << node.content if node.footnotes? && !(node.attr? 'nofootnotes') result << %(<div id="footnotes"> <hr#{@void_element_slash}>) node.footnotes.each do |footnote| result << %(<div class="footnote" id="_footnote_#{footnote.index}"> <a href="#_footnoteref_#{footnote.index}">#{footnote.index}</a> #{footnote.text} </div>) end result << '</div>' end result * EOL end def outline node, opts = {} return if (sections = node.sections).empty? sectnumlevels = opts[:sectnumlevels] || (node.document.attr 'sectnumlevels', 3).to_i toclevels = opts[:toclevels] || (node.document.attr 'toclevels', 2).to_i result = [] # FIXME the level for special sections should be set correctly in the model # slevel will only be 0 if we have a book doctype with parts slevel = (first_section = sections[0]).level slevel = 1 if slevel == 0 && first_section.special result << %(<ul class="sectlevel#{slevel}">) sections.each do |section| section_num = (section.numbered && !section.caption && section.level <= sectnumlevels) ? %(#{section.sectnum} ) : nil if section.level < toclevels && (child_toc_level = outline section, :toclevels => toclevels, :secnumlevels => sectnumlevels) result << %(<li><a href="##{section.id}">#{section_num}#{section.captioned_title}</a>) result << child_toc_level result << '</li>' else result << %(<li><a href="##{section.id}">#{section_num}#{section.captioned_title}</a></li>) end end result << '</ul>' result * EOL end def section node slevel = node.level # QUESTION should the check for slevel be done in section? slevel = 1 if slevel == 0 && node.special htag = %(h#{slevel + 1}) id_attr = anchor = link_start = link_end = nil if node.id id_attr = %( id="#{node.id}") if node.document.attr? 'sectanchors' anchor = %(<a class="anchor" href="##{node.id}"></a>) # possible idea - anchor icons GitHub-style #if node.document.attr? 'icons', 'font' # anchor = %(<a class="anchor" href="##{node.id}"><i class="fa fa-anchor"></i></a>) #else elsif node.document.attr? 'sectlinks' link_start = %(<a class="link" href="##{node.id}">) link_end = '</a>' end end if slevel == 0 %(<h1#{id_attr} class="sect0">#{anchor}#{link_start}#{node.title}#{link_end}</h1> #{node.content}) else class_attr = (role = node.role) ? %( class="sect#{slevel} #{role}") : %( class="sect#{slevel}") sectnum = if node.numbered && !node.caption && slevel <= (node.document.attr 'sectnumlevels', 3).to_i %(#{node.sectnum} ) end %(<div#{class_attr}> <#{htag}#{id_attr}>#{anchor}#{link_start}#{sectnum}#{node.captioned_title}#{link_end}</#{htag}> #{slevel == 1 ? %[<div class="sectionbody">\n#{node.content}\n</div>] : node.content} </div>) end end def admonition node id_attr = node.id ? %( id="#{node.id}") : nil name = node.attr 'name' title_element = node.title? ? %(<div class="title">#{node.title}</div>\n) : nil caption = if node.document.attr? 'icons' if node.document.attr? 'icons', 'font' %(<i class="fa icon-#{name}" title="#{node.caption}"></i>) else %(<img src="#{node.icon_uri name}" alt="#{node.caption}"#{@void_element_slash}>) end else %(<div class="title">#{node.caption}</div>) end %(<div#{id_attr} class="admonitionblock #{name}#{(role = node.role) && " #{role}"}"> <table> <tr> <td class="icon"> #{caption} </td> <td class="content"> #{title_element}#{node.content} </td> </tr> </table> </div>) end def audio node xml = node.document.attr? 'htmlsyntax', 'xml' id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['audioblock', node.style, node.role].compact class_attribute = %( class="#{classes * ' '}") title_element = node.title? ? %(<div class="title">#{node.captioned_title}</div>\n) : nil %(<div#{id_attribute}#{class_attribute}> #{title_element}<div class="content"> <audio src="#{node.media_uri(node.attr 'target')}"#{(node.option? 'autoplay') ? (append_boolean_attribute 'autoplay', xml) : nil}#{(node.option? 'nocontrols') ? nil : (append_boolean_attribute 'controls', xml)}#{(node.option? 'loop') ? (append_boolean_attribute 'loop', xml) : nil}> Your browser does not support the audio tag. </audio> </div> </div>) end def colist node result = [] id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['colist', node.style, node.role].compact class_attribute = %( class="#{classes * ' '}") result << %(<div#{id_attribute}#{class_attribute}>) result << %(<div class="title">#{node.title}</div>) if node.title? if node.document.attr? 'icons' result << '<table>' font_icons = node.document.attr? 'icons', 'font' node.items.each_with_index do |item, i| num = i + 1 num_element = if font_icons %(<i class="conum" data-value="#{num}"></i><b>#{num}</b>) else %(<img src="#{node.icon_uri "callouts/#{num}"}" alt="#{num}"#{@void_element_slash}>) end result << %(<tr> <td>#{num_element}</td> <td>#{item.text}</td> </tr>) end result << '</table>' else result << '<ol>' node.items.each do |item| result << %(<li> <p>#{item.text}</p> </li>) end result << '</ol>' end result << '</div>' result * EOL end def dlist node result = [] id_attribute = node.id ? %( id="#{node.id}") : nil classes = case node.style when 'qanda' ['qlist', 'qanda', node.role] when 'horizontal' ['hdlist', node.role] else ['dlist', node.style, node.role] end.compact class_attribute = %( class="#{classes * ' '}") result << %(<div#{id_attribute}#{class_attribute}>) result << %(<div class="title">#{node.title}</div>) if node.title? case node.style when 'qanda' result << '<ol>' node.items.each do |terms, dd| result << '<li>' [*terms].each do |dt| result << %(<p><em>#{dt.text}</em></p>) end if dd result << %(<p>#{dd.text}</p>) if dd.text? result << dd.content if dd.blocks? end result << '</li>' end result << '</ol>' when 'horizontal' slash = @void_element_slash result << '<table>' if (node.attr? 'labelwidth') || (node.attr? 'itemwidth') result << '<colgroup>' col_style_attribute = (node.attr? 'labelwidth') ? %( style="width: #{(node.attr 'labelwidth').chomp '%'}%;") : nil result << %(<col#{col_style_attribute}#{slash}>) col_style_attribute = (node.attr? 'itemwidth') ? %( style="width: #{(node.attr 'itemwidth').chomp '%'}%;") : nil result << %(<col#{col_style_attribute}#{slash}>) result << '</colgroup>' end node.items.each do |terms, dd| result << '<tr>' result << %(<td class="hdlist1#{(node.option? 'strong') ? ' strong' : nil}">) terms_array = [*terms] last_term = terms_array[-1] terms_array.each do |dt| result << dt.text result << %(<br#{slash}>) if dt != last_term end result << '</td>' result << '<td class="hdlist2">' if dd result << %(<p>#{dd.text}</p>) if dd.text? result << dd.content if dd.blocks? end result << '</td>' result << '</tr>' end result << '</table>' else result << '<dl>' dt_style_attribute = node.style ? nil : ' class="hdlist1"' node.items.each do |terms, dd| [*terms].each do |dt| result << %(<dt#{dt_style_attribute}>#{dt.text}</dt>) end if dd result << '<dd>' result << %(<p>#{dd.text}</p>) if dd.text? result << dd.content if dd.blocks? result << '</dd>' end end result << '</dl>' end result << '</div>' result * EOL end def example node id_attribute = node.id ? %( id="#{node.id}") : nil title_element = node.title? ? %(<div class="title">#{node.captioned_title}</div>\n) : nil %(<div#{id_attribute} class="#{(role = node.role) ? ['exampleblock', role] * ' ' : 'exampleblock'}"> #{title_element}<div class="content"> #{node.content} </div> </div>) end def floating_title node tag_name = %(h#{node.level + 1}) id_attribute = node.id ? %( id="#{node.id}") : nil classes = [node.style, node.role].compact %(<#{tag_name}#{id_attribute} class="#{classes * ' '}">#{node.title}</#{tag_name}>) end def image node align = (node.attr? 'align') ? (node.attr 'align') : nil float = (node.attr? 'float') ? (node.attr 'float') : nil style_attribute = if align || float styles = [align ? %(text-align: #{align}) : nil, float ? %(float: #{float}) : nil].compact %( style="#{styles * ';'}") end width_attribute = (node.attr? 'width') ? %( width="#{node.attr 'width'}") : nil height_attribute = (node.attr? 'height') ? %( height="#{node.attr 'height'}") : nil img_element = %(<img src="#{node.image_uri node.attr('target')}" alt="#{node.attr 'alt'}"#{width_attribute}#{height_attribute}#{@void_element_slash}>) if (link = node.attr 'link') img_element = %(<a class="image" href="#{link}">#{img_element}</a>) end id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['imageblock', node.style, node.role].compact class_attribute = %( class="#{classes * ' '}") title_element = node.title? ? %(\n<div class="title">#{node.captioned_title}</div>) : nil %(<div#{id_attribute}#{class_attribute}#{style_attribute}> <div class="content"> #{img_element} </div>#{title_element} </div>) end def listing node nowrap = !(node.document.attr? 'prewrap') || (node.option? 'nowrap') if node.style == 'source' if (language = node.attr 'language', nil, false) code_attrs = %( data-lang="#{language}") else code_attrs = nil end case node.document.attr 'source-highlighter' when 'coderay' pre_class = %( class="CodeRay highlight#{nowrap ? ' nowrap' : nil}") when 'pygments' pre_class = %( class="pygments highlight#{nowrap ? ' nowrap' : nil}") when 'highlightjs', 'highlight.js' pre_class = %( class="highlightjs highlight#{nowrap ? ' nowrap' : nil}") code_attrs = %( class="language-#{language}"#{code_attrs}) if language when 'prettify' pre_class = %( class="prettyprint highlight#{nowrap ? ' nowrap' : nil}#{(node.attr? 'linenums') ? ' linenums' : nil}") code_attrs = %( class="language-#{language}"#{code_attrs}) if language when 'html-pipeline' pre_class = language ? %( lang="#{language}") : nil code_attrs = nil else pre_class = %( class="highlight#{nowrap ? ' nowrap' : nil}") code_attrs = %( class="language-#{language}"#{code_attrs}) if language end pre_start = %(<pre#{pre_class}><code#{code_attrs}>) pre_end = '</code></pre>' else pre_start = %(<pre#{nowrap ? ' class="nowrap"' : nil}>) pre_end = '</pre>' end id_attribute = node.id ? %( id="#{node.id}") : nil title_element = node.title? ? %(<div class="title">#{node.captioned_title}</div>\n) : nil %(<div#{id_attribute} class="listingblock#{(role = node.role) && " #{role}"}"> #{title_element}<div class="content"> #{pre_start}#{node.content}#{pre_end} </div> </div>) end def literal node id_attribute = node.id ? %( id="#{node.id}") : nil title_element = node.title? ? %(<div class="title">#{node.title}</div>\n) : nil nowrap = !(node.document.attr? 'prewrap') || (node.option? 'nowrap') %(<div#{id_attribute} class="literalblock#{(role = node.role) && " #{role}"}"> #{title_element}<div class="content"> <pre#{nowrap ? ' class="nowrap"' : nil}>#{node.content}</pre> </div> </div>) end def stem node id_attribute = node.id ? %( id="#{node.id}") : nil title_element = node.title? ? %(<div class="title">#{node.title}</div>\n) : nil open, close = BLOCK_MATH_DELIMITERS[node.style.to_sym] unless ((equation = node.content).start_with? open) && (equation.end_with? close) equation = %(#{open}#{equation}#{close}) end %(<div#{id_attribute} class="#{(role = node.role) ? ['stemblock', role] * ' ' : 'stemblock'}"> #{title_element}<div class="content"> #{equation} </div> </div>) end def olist node result = [] id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['olist', node.style, node.role].compact class_attribute = %( class="#{classes * ' '}") result << %(<div#{id_attribute}#{class_attribute}>) result << %(<div class="title">#{node.title}</div>) if node.title? type_attribute = (keyword = node.list_marker_keyword) ? %( type="#{keyword}") : nil start_attribute = (node.attr? 'start') ? %( start="#{node.attr 'start'}") : nil result << %(<ol class="#{node.style}"#{type_attribute}#{start_attribute}>) node.items.each do |item| result << '<li>' result << %(<p>#{item.text}</p>) result << item.content if item.blocks? result << '</li>' end result << '</ol>' result << '</div>' result * EOL end def open node if (style = node.style) == 'abstract' if node.parent == node.document && node.document.doctype == 'book' warn 'asciidoctor: WARNING: abstract block cannot be used in a document without a title when doctype is book. Excluding block content.' '' else id_attr = node.id ? %( id="#{node.id}") : nil title_el = node.title? ? %(<div class="title">#{node.title}</div>) : nil %(<div#{id_attr} class="quoteblock abstract#{(role = node.role) && " #{role}"}"> #{title_el}<blockquote> #{node.content} </blockquote> </div>) end elsif style == 'partintro' && (node.level != 0 || node.parent.context != :section || node.document.doctype != 'book') warn 'asciidoctor: ERROR: partintro block can only be used when doctype is book and it\'s a child of a book part. Excluding block content.' '' else id_attr = node.id ? %( id="#{node.id}") : nil title_el = node.title? ? %(<div class="title">#{node.title}</div>) : nil %(<div#{id_attr} class="openblock#{style && style != 'open' ? " #{style}" : ''}#{(role = node.role) && " #{role}"}"> #{title_el}<div class="content"> #{node.content} </div> </div>) end end def page_break node '<div style="page-break-after: always;"></div>' end def paragraph node attributes = if node.id if node.role %( id="#{node.id}" class="paragraph #{node.role}") else %( id="#{node.id}" class="paragraph") end elsif node.role %( class="paragraph #{node.role}") else ' class="paragraph"' end if node.title? %(<div#{attributes}> <div class="title">#{node.title}</div> <p>#{node.content}</p> </div>) else %(<div#{attributes}> <p>#{node.content}</p> </div>) end end def preamble node toc = if (node.attr? 'toc') && (node.attr? 'toc-placement', 'preamble') %(\n<div id="toc" class="#{node.attr 'toc-class', 'toc'}"> <div id="toctitle">#{node.attr 'toc-title'}</div> #{outline node.document} </div>) end %(<div id="preamble"> <div class="sectionbody"> #{node.content} </div>#{toc} </div>) end def quote node id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['quoteblock', node.role].compact class_attribute = %( class="#{classes * ' '}") title_element = node.title? ? %(\n<div class="title">#{node.title}</div>) : nil attribution = (node.attr? 'attribution') ? (node.attr 'attribution') : nil citetitle = (node.attr? 'citetitle') ? (node.attr 'citetitle') : nil if attribution || citetitle cite_element = citetitle ? %(<cite>#{citetitle}</cite>) : nil attribution_text = attribution ? %(&#8212; #{attribution}#{citetitle ? "<br#{@void_element_slash}>\n" : nil}) : nil attribution_element = %(\n<div class="attribution">\n#{attribution_text}#{cite_element}\n</div>) else attribution_element = nil end %(<div#{id_attribute}#{class_attribute}>#{title_element} <blockquote> #{node.content} </blockquote>#{attribution_element} </div>) end def thematic_break node %(<hr#{@void_element_slash}>) end def sidebar node id_attribute = node.id ? %( id="#{node.id}") : nil title_element = node.title? ? %(<div class="title">#{node.title}</div>\n) : nil %(<div#{id_attribute} class="#{(role = node.role) ? ['sidebarblock', role] * ' ' : 'sidebarblock'}"> <div class="content"> #{title_element}#{node.content} </div> </div>) end def table node result = [] id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['tableblock', %(frame-#{node.attr 'frame', 'all'}), %(grid-#{node.attr 'grid', 'all'})] styles = [] unless node.option? 'autowidth' if (tablepcwidth = node.attr 'tablepcwidth') == 100 classes << 'spread' else styles << %(width: #{tablepcwidth}%;) end end if (role = node.role) classes << role end class_attribute = %( class="#{classes * ' '}") styles << %(float: #{node.attr 'float'};) if node.attr? 'float' style_attribute = styles.empty? ? nil : %( style="#{styles * ' '}") result << %(<table#{id_attribute}#{class_attribute}#{style_attribute}>) result << %(<caption class="title">#{node.captioned_title}</caption>) if node.title? if (node.attr 'rowcount') > 0 slash = @void_element_slash result << '<colgroup>' if node.option? 'autowidth' tag = %(<col#{slash}>) node.columns.size.times do result << tag end else node.columns.each do |col| result << %(<col style="width: #{col.attr 'colpcwidth'}%;"#{slash}>) end end result << '</colgroup>' [:head, :foot, :body].select {|tsec| !node.rows[tsec].empty? }.each do |tsec| result << %(<t#{tsec}>) node.rows[tsec].each do |row| result << '<tr>' row.each do |cell| if tsec == :head cell_content = cell.text else case cell.style when :asciidoc cell_content = %(<div>#{cell.content}</div>) when :verse cell_content = %(<div class="verse">#{cell.text}</div>) when :literal cell_content = %(<div class="literal"><pre>#{cell.text}</pre></div>) else cell_content = '' cell.content.each do |text| cell_content = %(#{cell_content}<p class="tableblock">#{text}</p>) end end end cell_tag_name = (tsec == :head || cell.style == :header ? 'th' : 'td') cell_class_attribute = %( class="tableblock halign-#{cell.attr 'halign'} valign-#{cell.attr 'valign'}") cell_colspan_attribute = cell.colspan ? %( colspan="#{cell.colspan}") : nil cell_rowspan_attribute = cell.rowspan ? %( rowspan="#{cell.rowspan}") : nil cell_style_attribute = (node.document.attr? 'cellbgcolor') ? %( style="background-color: #{node.document.attr 'cellbgcolor'};") : nil result << %(<#{cell_tag_name}#{cell_class_attribute}#{cell_colspan_attribute}#{cell_rowspan_attribute}#{cell_style_attribute}>#{cell_content}</#{cell_tag_name}>) end result << '</tr>' end result << %(</t#{tsec}>) end end result << '</table>' result * EOL end def toc node return '<!-- toc disabled -->' unless (doc = node.document).attr?('toc-placement', 'macro') && doc.attr?('toc') if node.id id_attr = %( id="#{node.id}") title_id_attr = %( id="#{node.id}title") else id_attr = ' id="toc"' title_id_attr = ' id="toctitle"' end title = node.title? ? node.title : (doc.attr 'toc-title') levels = (node.attr? 'levels') ? (node.attr 'levels').to_i : nil role = node.role? ? node.role : (doc.attr 'toc-class', 'toc') %(<div#{id_attr} class="#{role}"> <div#{title_id_attr} class="title">#{title}</div> #{outline doc, :toclevels => levels} </div>) end def ulist node result = [] id_attribute = node.id ? %( id="#{node.id}") : nil div_classes = ['ulist', node.style, node.role].compact marker_checked = nil marker_unchecked = nil if (checklist = node.option? 'checklist') div_classes.insert 1, 'checklist' ul_class_attribute = ' class="checklist"' if node.option? 'interactive' if node.document.attr? 'htmlsyntax', 'xml' marker_checked = '<input type="checkbox" data-item-complete="1" checked="checked"/> ' marker_unchecked = '<input type="checkbox" data-item-complete="0"/> ' else marker_checked = '<input type="checkbox" data-item-complete="1" checked> ' marker_unchecked = '<input type="checkbox" data-item-complete="0"> ' end else if node.document.attr? 'icons', 'font' marker_checked = '<i class="fa fa-check-square-o"></i> ' marker_unchecked = '<i class="fa fa-square-o"></i> ' else marker_checked = '&#10003; ' marker_unchecked = '&#10063; ' end end else ul_class_attribute = node.style ? %( class="#{node.style}") : nil end result << %(<div#{id_attribute} class="#{div_classes * ' '}">) result << %(<div class="title">#{node.title}</div>) if node.title? result << %(<ul#{ul_class_attribute}>) node.items.each do |item| result << '<li>' if checklist && (item.attr? 'checkbox') result << %(<p>#{(item.attr? 'checked') ? marker_checked : marker_unchecked}#{item.text}</p>) else result << %(<p>#{item.text}</p>) end result << item.content if item.blocks? result << '</li>' end result << '</ul>' result << '</div>' result * EOL end def verse node id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['verseblock', node.role].compact class_attribute = %( class="#{classes * ' '}") title_element = node.title? ? %(\n<div class="title">#{node.title}</div>) : nil attribution = (node.attr? 'attribution') ? (node.attr 'attribution') : nil citetitle = (node.attr? 'citetitle') ? (node.attr 'citetitle') : nil if attribution || citetitle cite_element = citetitle ? %(<cite>#{citetitle}</cite>) : nil attribution_text = attribution ? %(&#8212; #{attribution}#{citetitle ? "<br#{@void_element_slash}>\n" : nil}) : nil attribution_element = %(\n<div class="attribution">\n#{attribution_text}#{cite_element}\n</div>) else attribution_element = nil end %(<div#{id_attribute}#{class_attribute}>#{title_element} <pre class="content">#{node.content}</pre>#{attribution_element} </div>) end def video node xml = node.document.attr? 'htmlsyntax', 'xml' id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['videoblock', node.style, node.role].compact class_attribute = %( class="#{classes * ' '}") title_element = node.title? ? %(\n<div class="title">#{node.captioned_title}</div>) : nil width_attribute = (node.attr? 'width') ? %( width="#{node.attr 'width'}") : nil height_attribute = (node.attr? 'height') ? %( height="#{node.attr 'height'}") : nil case node.attr 'poster' when 'vimeo' unless (asset_uri_scheme = (node.document.attr 'asset-uri-scheme', 'https')).empty? asset_uri_scheme = %(#{asset_uri_scheme}:) end start_anchor = (node.attr? 'start', nil, false) ? %(#at=#{node.attr 'start'}) : nil delimiter = '?' autoplay_param = (node.option? 'autoplay') ? %(#{delimiter}autoplay=1) : nil delimiter = '&amp;' if autoplay_param loop_param = (node.option? 'loop') ? %(#{delimiter}loop=1) : nil %(<div#{id_attribute}#{class_attribute}>#{title_element} <div class="content"> <iframe#{width_attribute}#{height_attribute} src="#{asset_uri_scheme}//player.vimeo.com/video/#{node.attr 'target'}#{start_anchor}#{autoplay_param}#{loop_param}" frameborder="0"#{(node.option? 'nofullscreen') ? nil : (append_boolean_attribute 'allowfullscreen', xml)}></iframe> </div> </div>) when 'youtube' unless (asset_uri_scheme = (node.document.attr 'asset-uri-scheme', 'https')).empty? asset_uri_scheme = %(#{asset_uri_scheme}:) end rel_param_val = (node.option? 'related') ? 1 : 0 start_param = (node.attr? 'start', nil, false) ? %(&amp;start=#{node.attr 'start'}) : nil end_param = (node.attr? 'end', nil, false) ? %(&amp;end=#{node.attr 'end'}) : nil autoplay_param = (node.option? 'autoplay') ? '&amp;autoplay=1' : nil loop_param = (node.option? 'loop') ? '&amp;loop=1' : nil controls_param = (node.option? 'nocontrols') ? '&amp;controls=0' : nil # cover both ways of controlling fullscreen option if node.option? 'nofullscreen' fs_param = '&amp;fs=0' fs_attribute = nil else fs_param = nil fs_attribute = append_boolean_attribute 'allowfullscreen', xml end modest_param = (node.option? 'modest') ? '&amp;modestbranding=1' : nil theme_param = (node.attr? 'theme', nil, false) ? %(&amp;theme=#{node.attr 'theme'}) : nil hl_param = (node.attr? 'lang') ? %(&amp;hl=#{node.attr 'lang'}) : nil # parse video_id/list_id syntax where list_id (i.e., playlist) is optional target, list = (node.attr 'target').split '/', 2 if (list ||= (node.attr 'list', nil, false)) list_param = %(&amp;list=#{list}) else # parse dynamic playlist syntax: video_id1,video_id2,... target, playlist = target.split ',', 2 if (playlist ||= (node.attr 'playlist', nil, false)) # INFO playlist bar doesn't appear in Firefox unless showinfo=1 and modestbranding=1 list_param = %(&amp;playlist=#{playlist}) else list_param = nil end end %(<div#{id_attribute}#{class_attribute}>#{title_element} <div class="content"> <iframe#{width_attribute}#{height_attribute} src="#{asset_uri_scheme}//www.youtube.com/embed/#{target}?rel=#{rel_param_val}#{start_param}#{end_param}#{autoplay_param}#{loop_param}#{controls_param}#{list_param}#{fs_param}#{modest_param}#{theme_param}#{hl_param}" frameborder="0"#{fs_attribute}></iframe> </div> </div>) else poster_attribute = %(#{poster = node.attr 'poster'}).empty? ? nil : %( poster="#{node.media_uri poster}") start_t = node.attr 'start', nil, false end_t = node.attr 'end', nil, false time_anchor = (start_t || end_t) ? %(#t=#{start_t}#{end_t ? ',' : nil}#{end_t}) : nil %(<div#{id_attribute}#{class_attribute}>#{title_element} <div class="content"> <video src="#{node.media_uri(node.attr 'target')}#{time_anchor}"#{width_attribute}#{height_attribute}#{poster_attribute}#{(node.option? 'autoplay') ? (append_boolean_attribute 'autoplay', xml) : nil}#{(node.option? 'nocontrols') ? nil : (append_boolean_attribute 'controls', xml)}#{(node.option? 'loop') ? (append_boolean_attribute 'loop', xml) : nil}> Your browser does not support the video tag. </video> </div> </div>) end end def inline_anchor node target = node.target case node.type when :xref refid = node.attributes['refid'] || target # NOTE we lookup text in converter because DocBook doesn't need this logic text = node.text || (node.document.references[:ids][refid] || %([#{refid}])) # FIXME shouldn't target be refid? logic seems confused here %(<a href="#{target}">#{text}</a>) when :ref %(<a id="#{target}"></a>) when :link attrs = [] attrs << %( id="#{node.id}") if node.id if (role = node.role) attrs << %( class="#{role}") end attrs << %( title="#{node.attr 'title'}") if node.attr? 'title', nil, false attrs << %( target="#{node.attr 'window'}") if node.attr? 'window', nil, false %(<a href="#{target}"#{attrs.join}>#{node.text}</a>) when :bibref %(<a id="#{target}"></a>[#{target}]) else warn %(asciidoctor: WARNING: unknown anchor type: #{node.type.inspect}) end end def inline_break node %(#{node.text}<br#{@void_element_slash}>) end def inline_button node %(<b class="button">#{node.text}</b>) end def inline_callout node if node.document.attr? 'icons', 'font' %(<i class="conum" data-value="#{node.text}"></i><b>(#{node.text})</b>) elsif node.document.attr? 'icons' src = node.icon_uri("callouts/#{node.text}") %(<img src="#{src}" alt="#{node.text}"#{@void_element_slash}>) else %(<b class="conum">(#{node.text})</b>) end end def inline_footnote node if (index = node.attr 'index') if node.type == :xref %(<span class="footnoteref">[<a class="footnote" href="#_footnote_#{index}" title="View footnote.">#{index}</a>]</span>) else id_attr = node.id ? %( id="_footnote_#{node.id}") : nil %(<span class="footnote"#{id_attr}>[<a id="_footnoteref_#{index}" class="footnote" href="#_footnote_#{index}" title="View footnote.">#{index}</a>]</span>) end elsif node.type == :xref %(<span class="footnoteref red" title="Unresolved footnote reference.">[#{node.text}]</span>) end end def inline_image node if (type = node.type) == 'icon' && (node.document.attr? 'icons', 'font') style_class = %(fa fa-#{node.target}) if node.attr? 'size' style_class = %(#{style_class} fa-#{node.attr 'size'}) end if node.attr? 'rotate' style_class = %(#{style_class} fa-rotate-#{node.attr 'rotate'}) end if node.attr? 'flip' style_class = %(#{style_class} fa-flip-#{node.attr 'flip'}) end title_attribute = (node.attr? 'title') ? %( title="#{node.attr 'title'}") : nil img = %(<i class="#{style_class}"#{title_attribute}></i>) elsif type == 'icon' && !(node.document.attr? 'icons') img = %([#{node.attr 'alt'}]) else resolved_target = (type == 'icon') ? (node.icon_uri node.target) : (node.image_uri node.target) attrs = ['alt', 'width', 'height', 'title'].map {|name| (node.attr? name) ? %( #{name}="#{node.attr name}") : nil }.join img = %(<img src="#{resolved_target}"#{attrs}#{@void_element_slash}>) end if node.attr? 'link' window_attr = (node.attr? 'window') ? %( target="#{node.attr 'window'}") : nil img = %(<a class="image" href="#{node.attr 'link'}"#{window_attr}>#{img}</a>) end style_classes = (role = node.role) ? %(#{type} #{role}) : type style_attr = (node.attr? 'float') ? %( style="float: #{node.attr 'float'}") : nil %(<span class="#{style_classes}"#{style_attr}>#{img}</span>) end def inline_indexterm node node.type == :visible ? node.text : '' end def inline_kbd node if (keys = node.attr 'keys').size == 1 %(<kbd>#{keys[0]}</kbd>) else key_combo = keys.map {|key| %(<kbd>#{key}</kbd>+) }.join.chop %(<span class="keyseq">#{key_combo}</span>) end end def inline_menu node menu = node.attr 'menu' if !(submenus = node.attr 'submenus').empty? submenu_path = submenus.map {|submenu| %(<span class="submenu">#{submenu}</span>&#160;&#9656; ) }.join.chop %(<span class="menuseq"><span class="menu">#{menu}</span>&#160;&#9656; #{submenu_path} <span class="menuitem">#{node.attr 'menuitem'}</span></span>) elsif (menuitem = node.attr 'menuitem') %(<span class="menuseq"><span class="menu">#{menu}</span>&#160;&#9656; <span class="menuitem">#{menuitem}</span></span>) else %(<span class="menu">#{menu}</span>) end end def inline_quoted node open, close, is_tag = QUOTE_TAGS[node.type] if (role = node.role) if is_tag quoted_text = %(#{open.chop} class="#{role}">#{node.text}#{close}) else quoted_text = %(<span class="#{role}">#{open}#{node.text}#{close}</span>) end else quoted_text = %(#{open}#{node.text}#{close}) end node.id ? %(<a id="#{node.id}"></a>#{quoted_text}) : quoted_text end def append_boolean_attribute name, xml xml ? %( #{name}="#{name}") : %( #{name}) end end end consolidate code in the paragraph converter # encoding: UTF-8 module Asciidoctor # A built-in {Converter} implementation that generates HTML 5 output # consistent with the html5 backend from AsciiDoc Python. class Converter::Html5Converter < Converter::BuiltIn QUOTE_TAGS = { :emphasis => ['<em>', '</em>', true], :strong => ['<strong>', '</strong>', true], :monospaced => ['<code>', '</code>', true], :superscript => ['<sup>', '</sup>', true], :subscript => ['<sub>', '</sub>', true], :double => ['&#8220;', '&#8221;', false], :single => ['&#8216;', '&#8217;', false], :mark => ['<mark>', '</mark>', true], :asciimath => ['\\$', '\\$', false], :latexmath => ['\\(', '\\)', false] # Opal can't resolve these constants when referenced here #:asciimath => INLINE_MATH_DELIMITERS[:asciimath] + [false], #:latexmath => INLINE_MATH_DELIMITERS[:latexmath] + [false] } QUOTE_TAGS.default = [nil, nil, nil] def initialize backend, opts = {} @xml_mode = opts[:htmlsyntax] == 'xml' @void_element_slash = @xml_mode ? '/' : nil @stylesheets = Stylesheets.instance end def document node result = [] slash = @void_element_slash br = %(<br#{slash}>) unless (asset_uri_scheme = (node.attr 'asset-uri-scheme', 'https')).empty? asset_uri_scheme = %(#{asset_uri_scheme}:) end cdn_base = %(#{asset_uri_scheme}//cdnjs.cloudflare.com/ajax/libs) linkcss = node.safe >= SafeMode::SECURE || (node.attr? 'linkcss') result << '<!DOCTYPE html>' lang_attribute = (node.attr? 'nolang') ? nil : %( lang="#{node.attr 'lang', 'en'}") result << %(<html#{@xml_mode ? ' xmlns="http://www.w3.org/1999/xhtml"' : nil}#{lang_attribute}>) result << %(<head> <meta charset="#{node.attr 'encoding', 'UTF-8'}"#{slash}> <!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"#{slash}><![endif]--> <meta name="viewport" content="width=device-width, initial-scale=1.0"#{slash}> <meta name="generator" content="Asciidoctor #{node.attr 'asciidoctor-version'}"#{slash}>) result << %(<meta name="application-name" content="#{node.attr 'app-name'}"#{slash}>) if node.attr? 'app-name' result << %(<meta name="description" content="#{node.attr 'description'}"#{slash}>) if node.attr? 'description' result << %(<meta name="keywords" content="#{node.attr 'keywords'}"#{slash}>) if node.attr? 'keywords' result << %(<meta name="author" content="#{node.attr 'authors'}"#{slash}>) if node.attr? 'authors' result << %(<meta name="copyright" content="#{node.attr 'copyright'}"#{slash}>) if node.attr? 'copyright' result << %(<title>#{node.doctitle :sanitize => true, :use_fallback => true}</title>) if DEFAULT_STYLESHEET_KEYS.include?(node.attr 'stylesheet') if (webfonts = node.attr 'webfonts') result << %(<link rel="stylesheet" href="#{asset_uri_scheme}//fonts.googleapis.com/css?family=#{webfonts.empty? ? 'Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700' : webfonts}"#{slash}>) end if linkcss result << %(<link rel="stylesheet" href="#{node.normalize_web_path DEFAULT_STYLESHEET_NAME, (node.attr 'stylesdir', ''), false}"#{slash}>) else result << @stylesheets.embed_primary_stylesheet end elsif node.attr? 'stylesheet' if linkcss result << %(<link rel="stylesheet" href="#{node.normalize_web_path((node.attr 'stylesheet'), (node.attr 'stylesdir', ''))}"#{slash}>) else result << %(<style> #{node.read_asset node.normalize_system_path((node.attr 'stylesheet'), (node.attr 'stylesdir', '')), :warn_on_failure => true} </style>) end end if node.attr? 'icons', 'font' if node.attr? 'iconfont-remote' result << %(<link rel="stylesheet" href="#{node.attr 'iconfont-cdn', %[#{cdn_base}/font-awesome/4.3.0/css/font-awesome.min.css]}"#{slash}>) else iconfont_stylesheet = %(#{node.attr 'iconfont-name', 'font-awesome'}.css) result << %(<link rel="stylesheet" href="#{node.normalize_web_path iconfont_stylesheet, (node.attr 'stylesdir', ''), false}"#{slash}>) end end case (highlighter = node.attr 'source-highlighter') when 'coderay' if (node.attr 'coderay-css', 'class') == 'class' if linkcss result << %(<link rel="stylesheet" href="#{node.normalize_web_path @stylesheets.coderay_stylesheet_name, (node.attr 'stylesdir', ''), false}"#{slash}>) else result << @stylesheets.embed_coderay_stylesheet end end when 'pygments' if (node.attr 'pygments-css', 'class') == 'class' pygments_style = node.attr 'pygments-style' if linkcss result << %(<link rel="stylesheet" href="#{node.normalize_web_path @stylesheets.pygments_stylesheet_name(pygments_style), (node.attr 'stylesdir', ''), false}"#{slash}>) else result << (@stylesheets.embed_pygments_stylesheet pygments_style) end end end unless (docinfo_content = node.docinfo).empty? result << docinfo_content end result << '</head>' body_attrs = [] if node.id body_attrs << %(id="#{node.id}") end if (node.attr? 'toc-class') && (node.attr? 'toc') && (node.attr? 'toc-placement', 'auto') body_attrs << %(class="#{node.doctype} #{node.attr 'toc-class'} toc-#{node.attr 'toc-position', 'header'}") else body_attrs << %(class="#{node.doctype}") end if node.attr? 'max-width' body_attrs << %(style="max-width: #{node.attr 'max-width'};") end result << %(<body #{body_attrs * ' '}>) unless node.noheader result << '<div id="header">' if node.doctype == 'manpage' result << %(<h1>#{node.doctitle} Manual Page</h1>) if (node.attr? 'toc') && (node.attr? 'toc-placement', 'auto') result << %(<div id="toc" class="#{node.attr 'toc-class', 'toc'}"> <div id="toctitle">#{node.attr 'toc-title'}</div> #{outline node} </div>) end result << %(<h2>#{node.attr 'manname-title'}</h2> <div class="sectionbody"> <p>#{node.attr 'manname'} - #{node.attr 'manpurpose'}</p> </div>) else if node.has_header? result << %(<h1>#{node.header.title}</h1>) unless node.notitle details = [] if node.attr? 'author' details << %(<span id="author" class="author">#{node.attr 'author'}</span>#{br}) if node.attr? 'email' details << %(<span id="email" class="email">#{node.sub_macros(node.attr 'email')}</span>#{br}) end if (authorcount = (node.attr 'authorcount').to_i) > 1 (2..authorcount).each do |idx| details << %(<span id="author#{idx}" class="author">#{node.attr "author_#{idx}"}</span>#{br}) if node.attr? %(email_#{idx}) details << %(<span id="email#{idx}" class="email">#{node.sub_macros(node.attr "email_#{idx}")}</span>#{br}) end end end end if node.attr? 'revnumber' details << %(<span id="revnumber">#{((node.attr 'version-label') || '').downcase} #{node.attr 'revnumber'}#{(node.attr? 'revdate') ? ',' : ''}</span>) end if node.attr? 'revdate' details << %(<span id="revdate">#{node.attr 'revdate'}</span>) end if node.attr? 'revremark' details << %(#{br}<span id="revremark">#{node.attr 'revremark'}</span>) end unless details.empty? result << '<div class="details">' result.concat details result << '</div>' end end if (node.attr? 'toc') && (node.attr? 'toc-placement', 'auto') result << %(<div id="toc" class="#{node.attr 'toc-class', 'toc'}"> <div id="toctitle">#{node.attr 'toc-title'}</div> #{outline node} </div>) end end result << '</div>' end result << %(<div id="content"> #{node.content} </div>) if node.footnotes? && !(node.attr? 'nofootnotes') result << %(<div id="footnotes"> <hr#{slash}>) node.footnotes.each do |footnote| result << %(<div class="footnote" id="_footnote_#{footnote.index}"> <a href="#_footnoteref_#{footnote.index}">#{footnote.index}</a>. #{footnote.text} </div>) end result << '</div>' end unless node.nofooter result << '<div id="footer">' result << '<div id="footer-text">' if node.attr? 'revnumber' result << %(#{node.attr 'version-label'} #{node.attr 'revnumber'}#{br}) end if node.attr? 'last-update-label' result << %(#{node.attr 'last-update-label'} #{node.attr 'docdatetime'}) end result << '</div>' unless (docinfo_content = node.docinfo :footer).empty? result << docinfo_content end result << '</div>' end # Load Javascript at the end of body for performance # See http://www.html5rocks.com/en/tutorials/speed/script-loading/ case highlighter when 'highlightjs', 'highlight.js' highlightjs_path = node.attr 'highlightjsdir', %(#{cdn_base}/highlight.js/8.6) result << %(<link rel="stylesheet" href="#{highlightjs_path}/styles/#{node.attr 'highlightjs-theme', 'github'}.min.css"#{slash}>) result << %(<script src="#{highlightjs_path}/highlight.min.js"></script> <script>hljs.initHighlighting()</script>) when 'prettify' prettify_path = node.attr 'prettifydir', %(#{cdn_base}/prettify/r298) result << %(<link rel="stylesheet" href="#{prettify_path}/#{node.attr 'prettify-theme', 'prettify'}.min.css"#{slash}>) result << %(<script src="#{prettify_path}/prettify.min.js"></script> <script>prettyPrint()</script>) end if node.attr? 'stem' # IMPORTANT to_s calls on delimiter arrays are intentional for JavaScript compat (emulates JSON.stringify) eqnums_val = node.attr 'eqnums', 'none' eqnums_val = 'AMS' if eqnums_val == '' eqnums_opt = %( equationNumbers: { autoNumber: "#{eqnums_val}" } ) result << %(<script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: { inlineMath: [#{INLINE_MATH_DELIMITERS[:latexmath].inspect}], displayMath: [#{BLOCK_MATH_DELIMITERS[:latexmath].inspect}], ignoreClass: "nostem|nolatexmath" }, asciimath2jax: { delimiters: [#{BLOCK_MATH_DELIMITERS[:asciimath].inspect}], ignoreClass: "nostem|noasciimath" }, TeX: {#{eqnums_opt}} }); </script> <script src="#{cdn_base}/mathjax/2.4.0/MathJax.js?config=TeX-MML-AM_HTMLorMML"></script>) end result << '</body>' result << '</html>' result * EOL end def embedded node result = [] if !node.notitle && node.has_header? id_attr = node.id ? %( id="#{node.id}") : nil result << %(<h1#{id_attr}>#{node.header.title}</h1>) end result << node.content if node.footnotes? && !(node.attr? 'nofootnotes') result << %(<div id="footnotes"> <hr#{@void_element_slash}>) node.footnotes.each do |footnote| result << %(<div class="footnote" id="_footnote_#{footnote.index}"> <a href="#_footnoteref_#{footnote.index}">#{footnote.index}</a> #{footnote.text} </div>) end result << '</div>' end result * EOL end def outline node, opts = {} return if (sections = node.sections).empty? sectnumlevels = opts[:sectnumlevels] || (node.document.attr 'sectnumlevels', 3).to_i toclevels = opts[:toclevels] || (node.document.attr 'toclevels', 2).to_i result = [] # FIXME the level for special sections should be set correctly in the model # slevel will only be 0 if we have a book doctype with parts slevel = (first_section = sections[0]).level slevel = 1 if slevel == 0 && first_section.special result << %(<ul class="sectlevel#{slevel}">) sections.each do |section| section_num = (section.numbered && !section.caption && section.level <= sectnumlevels) ? %(#{section.sectnum} ) : nil if section.level < toclevels && (child_toc_level = outline section, :toclevels => toclevels, :secnumlevels => sectnumlevels) result << %(<li><a href="##{section.id}">#{section_num}#{section.captioned_title}</a>) result << child_toc_level result << '</li>' else result << %(<li><a href="##{section.id}">#{section_num}#{section.captioned_title}</a></li>) end end result << '</ul>' result * EOL end def section node slevel = node.level # QUESTION should the check for slevel be done in section? slevel = 1 if slevel == 0 && node.special htag = %(h#{slevel + 1}) id_attr = anchor = link_start = link_end = nil if node.id id_attr = %( id="#{node.id}") if node.document.attr? 'sectanchors' anchor = %(<a class="anchor" href="##{node.id}"></a>) # possible idea - anchor icons GitHub-style #if node.document.attr? 'icons', 'font' # anchor = %(<a class="anchor" href="##{node.id}"><i class="fa fa-anchor"></i></a>) #else elsif node.document.attr? 'sectlinks' link_start = %(<a class="link" href="##{node.id}">) link_end = '</a>' end end if slevel == 0 %(<h1#{id_attr} class="sect0">#{anchor}#{link_start}#{node.title}#{link_end}</h1> #{node.content}) else class_attr = (role = node.role) ? %( class="sect#{slevel} #{role}") : %( class="sect#{slevel}") sectnum = if node.numbered && !node.caption && slevel <= (node.document.attr 'sectnumlevels', 3).to_i %(#{node.sectnum} ) end %(<div#{class_attr}> <#{htag}#{id_attr}>#{anchor}#{link_start}#{sectnum}#{node.captioned_title}#{link_end}</#{htag}> #{slevel == 1 ? %[<div class="sectionbody">\n#{node.content}\n</div>] : node.content} </div>) end end def admonition node id_attr = node.id ? %( id="#{node.id}") : nil name = node.attr 'name' title_element = node.title? ? %(<div class="title">#{node.title}</div>\n) : nil caption = if node.document.attr? 'icons' if node.document.attr? 'icons', 'font' %(<i class="fa icon-#{name}" title="#{node.caption}"></i>) else %(<img src="#{node.icon_uri name}" alt="#{node.caption}"#{@void_element_slash}>) end else %(<div class="title">#{node.caption}</div>) end %(<div#{id_attr} class="admonitionblock #{name}#{(role = node.role) && " #{role}"}"> <table> <tr> <td class="icon"> #{caption} </td> <td class="content"> #{title_element}#{node.content} </td> </tr> </table> </div>) end def audio node xml = node.document.attr? 'htmlsyntax', 'xml' id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['audioblock', node.style, node.role].compact class_attribute = %( class="#{classes * ' '}") title_element = node.title? ? %(<div class="title">#{node.captioned_title}</div>\n) : nil %(<div#{id_attribute}#{class_attribute}> #{title_element}<div class="content"> <audio src="#{node.media_uri(node.attr 'target')}"#{(node.option? 'autoplay') ? (append_boolean_attribute 'autoplay', xml) : nil}#{(node.option? 'nocontrols') ? nil : (append_boolean_attribute 'controls', xml)}#{(node.option? 'loop') ? (append_boolean_attribute 'loop', xml) : nil}> Your browser does not support the audio tag. </audio> </div> </div>) end def colist node result = [] id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['colist', node.style, node.role].compact class_attribute = %( class="#{classes * ' '}") result << %(<div#{id_attribute}#{class_attribute}>) result << %(<div class="title">#{node.title}</div>) if node.title? if node.document.attr? 'icons' result << '<table>' font_icons = node.document.attr? 'icons', 'font' node.items.each_with_index do |item, i| num = i + 1 num_element = if font_icons %(<i class="conum" data-value="#{num}"></i><b>#{num}</b>) else %(<img src="#{node.icon_uri "callouts/#{num}"}" alt="#{num}"#{@void_element_slash}>) end result << %(<tr> <td>#{num_element}</td> <td>#{item.text}</td> </tr>) end result << '</table>' else result << '<ol>' node.items.each do |item| result << %(<li> <p>#{item.text}</p> </li>) end result << '</ol>' end result << '</div>' result * EOL end def dlist node result = [] id_attribute = node.id ? %( id="#{node.id}") : nil classes = case node.style when 'qanda' ['qlist', 'qanda', node.role] when 'horizontal' ['hdlist', node.role] else ['dlist', node.style, node.role] end.compact class_attribute = %( class="#{classes * ' '}") result << %(<div#{id_attribute}#{class_attribute}>) result << %(<div class="title">#{node.title}</div>) if node.title? case node.style when 'qanda' result << '<ol>' node.items.each do |terms, dd| result << '<li>' [*terms].each do |dt| result << %(<p><em>#{dt.text}</em></p>) end if dd result << %(<p>#{dd.text}</p>) if dd.text? result << dd.content if dd.blocks? end result << '</li>' end result << '</ol>' when 'horizontal' slash = @void_element_slash result << '<table>' if (node.attr? 'labelwidth') || (node.attr? 'itemwidth') result << '<colgroup>' col_style_attribute = (node.attr? 'labelwidth') ? %( style="width: #{(node.attr 'labelwidth').chomp '%'}%;") : nil result << %(<col#{col_style_attribute}#{slash}>) col_style_attribute = (node.attr? 'itemwidth') ? %( style="width: #{(node.attr 'itemwidth').chomp '%'}%;") : nil result << %(<col#{col_style_attribute}#{slash}>) result << '</colgroup>' end node.items.each do |terms, dd| result << '<tr>' result << %(<td class="hdlist1#{(node.option? 'strong') ? ' strong' : nil}">) terms_array = [*terms] last_term = terms_array[-1] terms_array.each do |dt| result << dt.text result << %(<br#{slash}>) if dt != last_term end result << '</td>' result << '<td class="hdlist2">' if dd result << %(<p>#{dd.text}</p>) if dd.text? result << dd.content if dd.blocks? end result << '</td>' result << '</tr>' end result << '</table>' else result << '<dl>' dt_style_attribute = node.style ? nil : ' class="hdlist1"' node.items.each do |terms, dd| [*terms].each do |dt| result << %(<dt#{dt_style_attribute}>#{dt.text}</dt>) end if dd result << '<dd>' result << %(<p>#{dd.text}</p>) if dd.text? result << dd.content if dd.blocks? result << '</dd>' end end result << '</dl>' end result << '</div>' result * EOL end def example node id_attribute = node.id ? %( id="#{node.id}") : nil title_element = node.title? ? %(<div class="title">#{node.captioned_title}</div>\n) : nil %(<div#{id_attribute} class="#{(role = node.role) ? ['exampleblock', role] * ' ' : 'exampleblock'}"> #{title_element}<div class="content"> #{node.content} </div> </div>) end def floating_title node tag_name = %(h#{node.level + 1}) id_attribute = node.id ? %( id="#{node.id}") : nil classes = [node.style, node.role].compact %(<#{tag_name}#{id_attribute} class="#{classes * ' '}">#{node.title}</#{tag_name}>) end def image node align = (node.attr? 'align') ? (node.attr 'align') : nil float = (node.attr? 'float') ? (node.attr 'float') : nil style_attribute = if align || float styles = [align ? %(text-align: #{align}) : nil, float ? %(float: #{float}) : nil].compact %( style="#{styles * ';'}") end width_attribute = (node.attr? 'width') ? %( width="#{node.attr 'width'}") : nil height_attribute = (node.attr? 'height') ? %( height="#{node.attr 'height'}") : nil img_element = %(<img src="#{node.image_uri node.attr('target')}" alt="#{node.attr 'alt'}"#{width_attribute}#{height_attribute}#{@void_element_slash}>) if (link = node.attr 'link') img_element = %(<a class="image" href="#{link}">#{img_element}</a>) end id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['imageblock', node.style, node.role].compact class_attribute = %( class="#{classes * ' '}") title_element = node.title? ? %(\n<div class="title">#{node.captioned_title}</div>) : nil %(<div#{id_attribute}#{class_attribute}#{style_attribute}> <div class="content"> #{img_element} </div>#{title_element} </div>) end def listing node nowrap = !(node.document.attr? 'prewrap') || (node.option? 'nowrap') if node.style == 'source' if (language = node.attr 'language', nil, false) code_attrs = %( data-lang="#{language}") else code_attrs = nil end case node.document.attr 'source-highlighter' when 'coderay' pre_class = %( class="CodeRay highlight#{nowrap ? ' nowrap' : nil}") when 'pygments' pre_class = %( class="pygments highlight#{nowrap ? ' nowrap' : nil}") when 'highlightjs', 'highlight.js' pre_class = %( class="highlightjs highlight#{nowrap ? ' nowrap' : nil}") code_attrs = %( class="language-#{language}"#{code_attrs}) if language when 'prettify' pre_class = %( class="prettyprint highlight#{nowrap ? ' nowrap' : nil}#{(node.attr? 'linenums') ? ' linenums' : nil}") code_attrs = %( class="language-#{language}"#{code_attrs}) if language when 'html-pipeline' pre_class = language ? %( lang="#{language}") : nil code_attrs = nil else pre_class = %( class="highlight#{nowrap ? ' nowrap' : nil}") code_attrs = %( class="language-#{language}"#{code_attrs}) if language end pre_start = %(<pre#{pre_class}><code#{code_attrs}>) pre_end = '</code></pre>' else pre_start = %(<pre#{nowrap ? ' class="nowrap"' : nil}>) pre_end = '</pre>' end id_attribute = node.id ? %( id="#{node.id}") : nil title_element = node.title? ? %(<div class="title">#{node.captioned_title}</div>\n) : nil %(<div#{id_attribute} class="listingblock#{(role = node.role) && " #{role}"}"> #{title_element}<div class="content"> #{pre_start}#{node.content}#{pre_end} </div> </div>) end def literal node id_attribute = node.id ? %( id="#{node.id}") : nil title_element = node.title? ? %(<div class="title">#{node.title}</div>\n) : nil nowrap = !(node.document.attr? 'prewrap') || (node.option? 'nowrap') %(<div#{id_attribute} class="literalblock#{(role = node.role) && " #{role}"}"> #{title_element}<div class="content"> <pre#{nowrap ? ' class="nowrap"' : nil}>#{node.content}</pre> </div> </div>) end def stem node id_attribute = node.id ? %( id="#{node.id}") : nil title_element = node.title? ? %(<div class="title">#{node.title}</div>\n) : nil open, close = BLOCK_MATH_DELIMITERS[node.style.to_sym] unless ((equation = node.content).start_with? open) && (equation.end_with? close) equation = %(#{open}#{equation}#{close}) end %(<div#{id_attribute} class="#{(role = node.role) ? ['stemblock', role] * ' ' : 'stemblock'}"> #{title_element}<div class="content"> #{equation} </div> </div>) end def olist node result = [] id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['olist', node.style, node.role].compact class_attribute = %( class="#{classes * ' '}") result << %(<div#{id_attribute}#{class_attribute}>) result << %(<div class="title">#{node.title}</div>) if node.title? type_attribute = (keyword = node.list_marker_keyword) ? %( type="#{keyword}") : nil start_attribute = (node.attr? 'start') ? %( start="#{node.attr 'start'}") : nil result << %(<ol class="#{node.style}"#{type_attribute}#{start_attribute}>) node.items.each do |item| result << '<li>' result << %(<p>#{item.text}</p>) result << item.content if item.blocks? result << '</li>' end result << '</ol>' result << '</div>' result * EOL end def open node if (style = node.style) == 'abstract' if node.parent == node.document && node.document.doctype == 'book' warn 'asciidoctor: WARNING: abstract block cannot be used in a document without a title when doctype is book. Excluding block content.' '' else id_attr = node.id ? %( id="#{node.id}") : nil title_el = node.title? ? %(<div class="title">#{node.title}</div>) : nil %(<div#{id_attr} class="quoteblock abstract#{(role = node.role) && " #{role}"}"> #{title_el}<blockquote> #{node.content} </blockquote> </div>) end elsif style == 'partintro' && (node.level != 0 || node.parent.context != :section || node.document.doctype != 'book') warn 'asciidoctor: ERROR: partintro block can only be used when doctype is book and it\'s a child of a book part. Excluding block content.' '' else id_attr = node.id ? %( id="#{node.id}") : nil title_el = node.title? ? %(<div class="title">#{node.title}</div>) : nil %(<div#{id_attr} class="openblock#{style && style != 'open' ? " #{style}" : ''}#{(role = node.role) && " #{role}"}"> #{title_el}<div class="content"> #{node.content} </div> </div>) end end def page_break node '<div style="page-break-after: always;"></div>' end def paragraph node class_attribute = node.role ? %( class="#{node.role} paragraph") : ' class="paragraph"' attributes = node.id ? %( id="#{node.id}" #{class_attribute}) : class_attribute if node.title? %(<div#{attributes}> <div class="title">#{node.title}</div> <p>#{node.content}</p> </div>) else %(<div#{attributes}> <p>#{node.content}</p> </div>) end end def preamble node toc = if (node.attr? 'toc') && (node.attr? 'toc-placement', 'preamble') %(\n<div id="toc" class="#{node.attr 'toc-class', 'toc'}"> <div id="toctitle">#{node.attr 'toc-title'}</div> #{outline node.document} </div>) end %(<div id="preamble"> <div class="sectionbody"> #{node.content} </div>#{toc} </div>) end def quote node id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['quoteblock', node.role].compact class_attribute = %( class="#{classes * ' '}") title_element = node.title? ? %(\n<div class="title">#{node.title}</div>) : nil attribution = (node.attr? 'attribution') ? (node.attr 'attribution') : nil citetitle = (node.attr? 'citetitle') ? (node.attr 'citetitle') : nil if attribution || citetitle cite_element = citetitle ? %(<cite>#{citetitle}</cite>) : nil attribution_text = attribution ? %(&#8212; #{attribution}#{citetitle ? "<br#{@void_element_slash}>\n" : nil}) : nil attribution_element = %(\n<div class="attribution">\n#{attribution_text}#{cite_element}\n</div>) else attribution_element = nil end %(<div#{id_attribute}#{class_attribute}>#{title_element} <blockquote> #{node.content} </blockquote>#{attribution_element} </div>) end def thematic_break node %(<hr#{@void_element_slash}>) end def sidebar node id_attribute = node.id ? %( id="#{node.id}") : nil title_element = node.title? ? %(<div class="title">#{node.title}</div>\n) : nil %(<div#{id_attribute} class="#{(role = node.role) ? ['sidebarblock', role] * ' ' : 'sidebarblock'}"> <div class="content"> #{title_element}#{node.content} </div> </div>) end def table node result = [] id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['tableblock', %(frame-#{node.attr 'frame', 'all'}), %(grid-#{node.attr 'grid', 'all'})] styles = [] unless node.option? 'autowidth' if (tablepcwidth = node.attr 'tablepcwidth') == 100 classes << 'spread' else styles << %(width: #{tablepcwidth}%;) end end if (role = node.role) classes << role end class_attribute = %( class="#{classes * ' '}") styles << %(float: #{node.attr 'float'};) if node.attr? 'float' style_attribute = styles.empty? ? nil : %( style="#{styles * ' '}") result << %(<table#{id_attribute}#{class_attribute}#{style_attribute}>) result << %(<caption class="title">#{node.captioned_title}</caption>) if node.title? if (node.attr 'rowcount') > 0 slash = @void_element_slash result << '<colgroup>' if node.option? 'autowidth' tag = %(<col#{slash}>) node.columns.size.times do result << tag end else node.columns.each do |col| result << %(<col style="width: #{col.attr 'colpcwidth'}%;"#{slash}>) end end result << '</colgroup>' [:head, :foot, :body].select {|tsec| !node.rows[tsec].empty? }.each do |tsec| result << %(<t#{tsec}>) node.rows[tsec].each do |row| result << '<tr>' row.each do |cell| if tsec == :head cell_content = cell.text else case cell.style when :asciidoc cell_content = %(<div>#{cell.content}</div>) when :verse cell_content = %(<div class="verse">#{cell.text}</div>) when :literal cell_content = %(<div class="literal"><pre>#{cell.text}</pre></div>) else cell_content = '' cell.content.each do |text| cell_content = %(#{cell_content}<p class="tableblock">#{text}</p>) end end end cell_tag_name = (tsec == :head || cell.style == :header ? 'th' : 'td') cell_class_attribute = %( class="tableblock halign-#{cell.attr 'halign'} valign-#{cell.attr 'valign'}") cell_colspan_attribute = cell.colspan ? %( colspan="#{cell.colspan}") : nil cell_rowspan_attribute = cell.rowspan ? %( rowspan="#{cell.rowspan}") : nil cell_style_attribute = (node.document.attr? 'cellbgcolor') ? %( style="background-color: #{node.document.attr 'cellbgcolor'};") : nil result << %(<#{cell_tag_name}#{cell_class_attribute}#{cell_colspan_attribute}#{cell_rowspan_attribute}#{cell_style_attribute}>#{cell_content}</#{cell_tag_name}>) end result << '</tr>' end result << %(</t#{tsec}>) end end result << '</table>' result * EOL end def toc node return '<!-- toc disabled -->' unless (doc = node.document).attr?('toc-placement', 'macro') && doc.attr?('toc') if node.id id_attr = %( id="#{node.id}") title_id_attr = %( id="#{node.id}title") else id_attr = ' id="toc"' title_id_attr = ' id="toctitle"' end title = node.title? ? node.title : (doc.attr 'toc-title') levels = (node.attr? 'levels') ? (node.attr 'levels').to_i : nil role = node.role? ? node.role : (doc.attr 'toc-class', 'toc') %(<div#{id_attr} class="#{role}"> <div#{title_id_attr} class="title">#{title}</div> #{outline doc, :toclevels => levels} </div>) end def ulist node result = [] id_attribute = node.id ? %( id="#{node.id}") : nil div_classes = ['ulist', node.style, node.role].compact marker_checked = nil marker_unchecked = nil if (checklist = node.option? 'checklist') div_classes.insert 1, 'checklist' ul_class_attribute = ' class="checklist"' if node.option? 'interactive' if node.document.attr? 'htmlsyntax', 'xml' marker_checked = '<input type="checkbox" data-item-complete="1" checked="checked"/> ' marker_unchecked = '<input type="checkbox" data-item-complete="0"/> ' else marker_checked = '<input type="checkbox" data-item-complete="1" checked> ' marker_unchecked = '<input type="checkbox" data-item-complete="0"> ' end else if node.document.attr? 'icons', 'font' marker_checked = '<i class="fa fa-check-square-o"></i> ' marker_unchecked = '<i class="fa fa-square-o"></i> ' else marker_checked = '&#10003; ' marker_unchecked = '&#10063; ' end end else ul_class_attribute = node.style ? %( class="#{node.style}") : nil end result << %(<div#{id_attribute} class="#{div_classes * ' '}">) result << %(<div class="title">#{node.title}</div>) if node.title? result << %(<ul#{ul_class_attribute}>) node.items.each do |item| result << '<li>' if checklist && (item.attr? 'checkbox') result << %(<p>#{(item.attr? 'checked') ? marker_checked : marker_unchecked}#{item.text}</p>) else result << %(<p>#{item.text}</p>) end result << item.content if item.blocks? result << '</li>' end result << '</ul>' result << '</div>' result * EOL end def verse node id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['verseblock', node.role].compact class_attribute = %( class="#{classes * ' '}") title_element = node.title? ? %(\n<div class="title">#{node.title}</div>) : nil attribution = (node.attr? 'attribution') ? (node.attr 'attribution') : nil citetitle = (node.attr? 'citetitle') ? (node.attr 'citetitle') : nil if attribution || citetitle cite_element = citetitle ? %(<cite>#{citetitle}</cite>) : nil attribution_text = attribution ? %(&#8212; #{attribution}#{citetitle ? "<br#{@void_element_slash}>\n" : nil}) : nil attribution_element = %(\n<div class="attribution">\n#{attribution_text}#{cite_element}\n</div>) else attribution_element = nil end %(<div#{id_attribute}#{class_attribute}>#{title_element} <pre class="content">#{node.content}</pre>#{attribution_element} </div>) end def video node xml = node.document.attr? 'htmlsyntax', 'xml' id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['videoblock', node.style, node.role].compact class_attribute = %( class="#{classes * ' '}") title_element = node.title? ? %(\n<div class="title">#{node.captioned_title}</div>) : nil width_attribute = (node.attr? 'width') ? %( width="#{node.attr 'width'}") : nil height_attribute = (node.attr? 'height') ? %( height="#{node.attr 'height'}") : nil case node.attr 'poster' when 'vimeo' unless (asset_uri_scheme = (node.document.attr 'asset-uri-scheme', 'https')).empty? asset_uri_scheme = %(#{asset_uri_scheme}:) end start_anchor = (node.attr? 'start', nil, false) ? %(#at=#{node.attr 'start'}) : nil delimiter = '?' autoplay_param = (node.option? 'autoplay') ? %(#{delimiter}autoplay=1) : nil delimiter = '&amp;' if autoplay_param loop_param = (node.option? 'loop') ? %(#{delimiter}loop=1) : nil %(<div#{id_attribute}#{class_attribute}>#{title_element} <div class="content"> <iframe#{width_attribute}#{height_attribute} src="#{asset_uri_scheme}//player.vimeo.com/video/#{node.attr 'target'}#{start_anchor}#{autoplay_param}#{loop_param}" frameborder="0"#{(node.option? 'nofullscreen') ? nil : (append_boolean_attribute 'allowfullscreen', xml)}></iframe> </div> </div>) when 'youtube' unless (asset_uri_scheme = (node.document.attr 'asset-uri-scheme', 'https')).empty? asset_uri_scheme = %(#{asset_uri_scheme}:) end rel_param_val = (node.option? 'related') ? 1 : 0 start_param = (node.attr? 'start', nil, false) ? %(&amp;start=#{node.attr 'start'}) : nil end_param = (node.attr? 'end', nil, false) ? %(&amp;end=#{node.attr 'end'}) : nil autoplay_param = (node.option? 'autoplay') ? '&amp;autoplay=1' : nil loop_param = (node.option? 'loop') ? '&amp;loop=1' : nil controls_param = (node.option? 'nocontrols') ? '&amp;controls=0' : nil # cover both ways of controlling fullscreen option if node.option? 'nofullscreen' fs_param = '&amp;fs=0' fs_attribute = nil else fs_param = nil fs_attribute = append_boolean_attribute 'allowfullscreen', xml end modest_param = (node.option? 'modest') ? '&amp;modestbranding=1' : nil theme_param = (node.attr? 'theme', nil, false) ? %(&amp;theme=#{node.attr 'theme'}) : nil hl_param = (node.attr? 'lang') ? %(&amp;hl=#{node.attr 'lang'}) : nil # parse video_id/list_id syntax where list_id (i.e., playlist) is optional target, list = (node.attr 'target').split '/', 2 if (list ||= (node.attr 'list', nil, false)) list_param = %(&amp;list=#{list}) else # parse dynamic playlist syntax: video_id1,video_id2,... target, playlist = target.split ',', 2 if (playlist ||= (node.attr 'playlist', nil, false)) # INFO playlist bar doesn't appear in Firefox unless showinfo=1 and modestbranding=1 list_param = %(&amp;playlist=#{playlist}) else list_param = nil end end %(<div#{id_attribute}#{class_attribute}>#{title_element} <div class="content"> <iframe#{width_attribute}#{height_attribute} src="#{asset_uri_scheme}//www.youtube.com/embed/#{target}?rel=#{rel_param_val}#{start_param}#{end_param}#{autoplay_param}#{loop_param}#{controls_param}#{list_param}#{fs_param}#{modest_param}#{theme_param}#{hl_param}" frameborder="0"#{fs_attribute}></iframe> </div> </div>) else poster_attribute = %(#{poster = node.attr 'poster'}).empty? ? nil : %( poster="#{node.media_uri poster}") start_t = node.attr 'start', nil, false end_t = node.attr 'end', nil, false time_anchor = (start_t || end_t) ? %(#t=#{start_t}#{end_t ? ',' : nil}#{end_t}) : nil %(<div#{id_attribute}#{class_attribute}>#{title_element} <div class="content"> <video src="#{node.media_uri(node.attr 'target')}#{time_anchor}"#{width_attribute}#{height_attribute}#{poster_attribute}#{(node.option? 'autoplay') ? (append_boolean_attribute 'autoplay', xml) : nil}#{(node.option? 'nocontrols') ? nil : (append_boolean_attribute 'controls', xml)}#{(node.option? 'loop') ? (append_boolean_attribute 'loop', xml) : nil}> Your browser does not support the video tag. </video> </div> </div>) end end def inline_anchor node target = node.target case node.type when :xref refid = node.attributes['refid'] || target # NOTE we lookup text in converter because DocBook doesn't need this logic text = node.text || (node.document.references[:ids][refid] || %([#{refid}])) # FIXME shouldn't target be refid? logic seems confused here %(<a href="#{target}">#{text}</a>) when :ref %(<a id="#{target}"></a>) when :link attrs = [] attrs << %( id="#{node.id}") if node.id if (role = node.role) attrs << %( class="#{role}") end attrs << %( title="#{node.attr 'title'}") if node.attr? 'title', nil, false attrs << %( target="#{node.attr 'window'}") if node.attr? 'window', nil, false %(<a href="#{target}"#{attrs.join}>#{node.text}</a>) when :bibref %(<a id="#{target}"></a>[#{target}]) else warn %(asciidoctor: WARNING: unknown anchor type: #{node.type.inspect}) end end def inline_break node %(#{node.text}<br#{@void_element_slash}>) end def inline_button node %(<b class="button">#{node.text}</b>) end def inline_callout node if node.document.attr? 'icons', 'font' %(<i class="conum" data-value="#{node.text}"></i><b>(#{node.text})</b>) elsif node.document.attr? 'icons' src = node.icon_uri("callouts/#{node.text}") %(<img src="#{src}" alt="#{node.text}"#{@void_element_slash}>) else %(<b class="conum">(#{node.text})</b>) end end def inline_footnote node if (index = node.attr 'index') if node.type == :xref %(<span class="footnoteref">[<a class="footnote" href="#_footnote_#{index}" title="View footnote.">#{index}</a>]</span>) else id_attr = node.id ? %( id="_footnote_#{node.id}") : nil %(<span class="footnote"#{id_attr}>[<a id="_footnoteref_#{index}" class="footnote" href="#_footnote_#{index}" title="View footnote.">#{index}</a>]</span>) end elsif node.type == :xref %(<span class="footnoteref red" title="Unresolved footnote reference.">[#{node.text}]</span>) end end def inline_image node if (type = node.type) == 'icon' && (node.document.attr? 'icons', 'font') style_class = %(fa fa-#{node.target}) if node.attr? 'size' style_class = %(#{style_class} fa-#{node.attr 'size'}) end if node.attr? 'rotate' style_class = %(#{style_class} fa-rotate-#{node.attr 'rotate'}) end if node.attr? 'flip' style_class = %(#{style_class} fa-flip-#{node.attr 'flip'}) end title_attribute = (node.attr? 'title') ? %( title="#{node.attr 'title'}") : nil img = %(<i class="#{style_class}"#{title_attribute}></i>) elsif type == 'icon' && !(node.document.attr? 'icons') img = %([#{node.attr 'alt'}]) else resolved_target = (type == 'icon') ? (node.icon_uri node.target) : (node.image_uri node.target) attrs = ['alt', 'width', 'height', 'title'].map {|name| (node.attr? name) ? %( #{name}="#{node.attr name}") : nil }.join img = %(<img src="#{resolved_target}"#{attrs}#{@void_element_slash}>) end if node.attr? 'link' window_attr = (node.attr? 'window') ? %( target="#{node.attr 'window'}") : nil img = %(<a class="image" href="#{node.attr 'link'}"#{window_attr}>#{img}</a>) end style_classes = (role = node.role) ? %(#{type} #{role}) : type style_attr = (node.attr? 'float') ? %( style="float: #{node.attr 'float'}") : nil %(<span class="#{style_classes}"#{style_attr}>#{img}</span>) end def inline_indexterm node node.type == :visible ? node.text : '' end def inline_kbd node if (keys = node.attr 'keys').size == 1 %(<kbd>#{keys[0]}</kbd>) else key_combo = keys.map {|key| %(<kbd>#{key}</kbd>+) }.join.chop %(<span class="keyseq">#{key_combo}</span>) end end def inline_menu node menu = node.attr 'menu' if !(submenus = node.attr 'submenus').empty? submenu_path = submenus.map {|submenu| %(<span class="submenu">#{submenu}</span>&#160;&#9656; ) }.join.chop %(<span class="menuseq"><span class="menu">#{menu}</span>&#160;&#9656; #{submenu_path} <span class="menuitem">#{node.attr 'menuitem'}</span></span>) elsif (menuitem = node.attr 'menuitem') %(<span class="menuseq"><span class="menu">#{menu}</span>&#160;&#9656; <span class="menuitem">#{menuitem}</span></span>) else %(<span class="menu">#{menu}</span>) end end def inline_quoted node open, close, is_tag = QUOTE_TAGS[node.type] if (role = node.role) if is_tag quoted_text = %(#{open.chop} class="#{role}">#{node.text}#{close}) else quoted_text = %(<span class="#{role}">#{open}#{node.text}#{close}</span>) end else quoted_text = %(#{open}#{node.text}#{close}) end node.id ? %(<a id="#{node.id}"></a>#{quoted_text}) : quoted_text end def append_boolean_attribute name, xml xml ? %( #{name}="#{name}") : %( #{name}) end end end
module Awsborn class KnownHostsUpdater class << self attr_accessor :logger def update_for_server (server) known_hosts = new(server.ec2, server.host_name) known_hosts.update end def logger @logger ||= Awsborn.logger end end attr_accessor :ec2, :host_name, :host_ip, :console_fingerprint, :fingerprint_file, :logger def initialize (ec2, host_name) @host_name = host_name @ec2 = ec2 end def update tries = 0 begin tries += 1 try_update rescue SecurityError => e if tries < 5 logger.debug e.message logger.debug "Sleeping, try #{tries}" sleep([2**tries, 15].min) retry else raise e end end end def try_update get_console_fingerprint clean_out_known_hosts scan_hosts compare_fingerprints! save_fingerprints end def get_console_fingerprint # ec2: -----BEGIN SSH HOST KEY FINGERPRINTS----- # ec2: 2048 7a:e9:eb:41:b7:45:b1:07:30:ad:13:c5:a9:2a:a1:e5 /etc/ssh/ssh_host_rsa_key.pub (RSA) regexp = %r{BEGIN SSH HOST KEY FINGERPRINTS.*((?:[0-9a-f]{2}:){15}[0-9a-f]{2}) /etc/ssh/ssh_host_rsa_key.pub }m @console_fingerprint = Awsborn.wait_for "console output", 15, 420 do console = ec2.get_console_output if console.any? fingerprint = console[regexp, 1] if ! fingerprint logger.error "*** SSH RSA fingerprint not found ***" logger.error lines logger.error "*** SSH RSA fingerprint not found ***" end end fingerprint end end def clean_out_known_hosts remove_from_known_hosts host_name remove_from_known_hosts host_ip end def remove_from_known_hosts (host) system "ssh-keygen -R #{host} > /dev/null 2>&1" end def scan_hosts self.fingerprint_file = create_tempfile system "ssh-keyscan -t rsa #{host_name} #{host_ip} > #{fingerprint_file} 2>/dev/null" end def compare_fingerprints! name_fingerprint, ip_fingerprint = fingerprints_from_file if name_fingerprint.nil? || ip_fingerprint.nil? raise SecurityError, "name_fingerprint = #{name_fingerprint.inspect}, ip_fingerprint = #{ip_fingerprint.inspect}" elsif name_fingerprint.split[1] != ip_fingerprint.split[1] raise SecurityError, "Fingerprints do not match:\n#{name_fingerprint} (#{host_name})\n#{ip_fingerprint} (#{host_ip})!" elsif name_fingerprint.split[1] != console_fingerprint raise SecurityError, "Fingerprints do not match:\n#{name_fingerprint} (#{host_name})\n#{console_fingerprint} (EC2 Console)!" end end def fingerprints_from_file `ssh-keygen -l -f #{fingerprint_file}`.split("\n") end def save_fingerprints system "cat #{fingerprint_file} >> #{ENV['HOME']}/.ssh/known_hosts" end def create_tempfile tmp = Tempfile.new "awsborn" tmp.close def tmp.to_s path end tmp end def logger @logger ||= self.class.logger end def host_ip @host_ip ||= Resolv.getaddress host_name end end end Need longer timeout to handle the slow racks in us_east. module Awsborn class KnownHostsUpdater class << self attr_accessor :logger def update_for_server (server) known_hosts = new(server.ec2, server.host_name) known_hosts.update end def logger @logger ||= Awsborn.logger end end attr_accessor :ec2, :host_name, :host_ip, :console_fingerprint, :fingerprint_file, :logger def initialize (ec2, host_name) @host_name = host_name @ec2 = ec2 end def update tries = 0 begin tries += 1 try_update rescue SecurityError => e if tries < 8 logger.debug e.message sleep_time = [2**tries, 30].min logger.debug "Fingerprint try #{tries} failed, sleeping #{sleep_time} seconds" sleep(sleep_time) retry else raise e end end end def try_update get_console_fingerprint clean_out_known_hosts scan_hosts compare_fingerprints! save_fingerprints end def get_console_fingerprint # ec2: -----BEGIN SSH HOST KEY FINGERPRINTS----- # ec2: 2048 7a:e9:eb:41:b7:45:b1:07:30:ad:13:c5:a9:2a:a1:e5 /etc/ssh/ssh_host_rsa_key.pub (RSA) regexp = %r{BEGIN SSH HOST KEY FINGERPRINTS.*((?:[0-9a-f]{2}:){15}[0-9a-f]{2}) /etc/ssh/ssh_host_rsa_key.pub }m @console_fingerprint = Awsborn.wait_for "console output", 15, 420 do console = ec2.get_console_output if console.any? fingerprint = console[regexp, 1] if ! fingerprint logger.error "*** SSH RSA fingerprint not found ***" logger.error lines logger.error "*** SSH RSA fingerprint not found ***" end end fingerprint end end def clean_out_known_hosts remove_from_known_hosts host_name remove_from_known_hosts host_ip end def remove_from_known_hosts (host) system "ssh-keygen -R #{host} > /dev/null 2>&1" end def scan_hosts self.fingerprint_file = create_tempfile system "ssh-keyscan -t rsa #{host_name} #{host_ip} > #{fingerprint_file} 2>/dev/null" end def compare_fingerprints! name_fingerprint, ip_fingerprint = fingerprints_from_file if name_fingerprint.nil? || ip_fingerprint.nil? raise SecurityError, "name_fingerprint = #{name_fingerprint.inspect}, ip_fingerprint = #{ip_fingerprint.inspect}" elsif name_fingerprint.split[1] != ip_fingerprint.split[1] raise SecurityError, "Fingerprints do not match:\n#{name_fingerprint} (#{host_name})\n#{ip_fingerprint} (#{host_ip})!" elsif name_fingerprint.split[1] != console_fingerprint raise SecurityError, "Fingerprints do not match:\n#{name_fingerprint} (#{host_name})\n#{console_fingerprint} (EC2 Console)!" end end def fingerprints_from_file `ssh-keygen -l -f #{fingerprint_file}`.split("\n") end def save_fingerprints system "cat #{fingerprint_file} >> #{ENV['HOME']}/.ssh/known_hosts" end def create_tempfile tmp = Tempfile.new "awsborn" tmp.close def tmp.to_s path end tmp end def logger @logger ||= self.class.logger end def host_ip @host_ip ||= Resolv.getaddress host_name end end end
require_relative './file' module Builderator # :nodoc module Config ## # Global predefined defaults ## GLOBAL_DEFAULTS = File.new({}, :source => 'GLOBAL_DEFAULTS') do cleanup true version '0.0.0' build_number 0 autoversion do |autoversion| autoversion.create_tags true autoversion.search_tags true end local do |local| local.vendor_path 'vendor' local.cookbook_path 'cookbooks' local.staging_directory '/var/chef' end cookbook do |cookbook| cookbook.path = '.' cookbook.berkshelf_config = ::File.join(ENV['HOME'], '.berkshelf/config.json') cookbook.add_source 'https://supermarket.chef.io' end aws.region 'us-east-1' profile :default do |profile| profile.log_level :info profile.vagrant do |vagrant| vagrant.ec2 do |ec2| ec2.provider :aws ec2.box 'dummy' ec2.box_url 'https://github.com/mitchellh/vagrant-aws/raw/master/dummy.box' ec2.instance_type 't2.micro' ec2.public_ip true end vagrant.local do |local| local.provider :virtualbox local.box 'ubuntu-14.04-x86_64' local.box_url 'https://cloud-images.ubuntu.com/vagrant/trusty/'\ 'current/trusty-server-cloudimg-amd64-vagrant-disk1.box' local.memory 1024 local.cpus 2 end end profile.packer do |packer| packer.build :default do |build| build.type 'amazon-ebs' build.instance_type 'c3.large' build.ssh_username 'ubuntu' build.ami_virtualization_type 'hvm' ## The Packer task will ensure a re-compile is performed if Config.compiled? build.ami_name "#{ Config.build_name }-#{ Config.version }-#{ Config.build_number }" build.ami_description Config.description end end end end profile(:bake).extends :default cleaner do |cleaner| cleaner.commit false cleaner.force false cleaner.filters {} cleaner.sort_by 'creation_date' cleaner.keep 5 cleaner.limits do |limits| limits.images 24 limits.launch_configs 48 limits.snapshots 24 limits.volumes 8 end end generator.gemfile.vagrant do |vagrant| vagrant.install true vagrant.version 'v1.7.4' end generator.project :jetty do |jetty| jetty.berksfile :rm jetty.buildfile :sync jetty.gemfile :ignore jetty.gitignore :sync jetty.packerfile :rm jetty.vagrantfile :rm jetty.thorfile :rm jetty.cookbook :rm end ## Ensure that attributes[:vendor] is a populated vendor {} end end end Remove final usages of `Config.compiled?` and update Jetty generator parameters require_relative './file' module Builderator # :nodoc module Config ## # Global predefined defaults ## GLOBAL_DEFAULTS = File.new({}, :source => 'GLOBAL_DEFAULTS') do cleanup true version '0.0.0' build_number 0 autoversion do |autoversion| autoversion.create_tags true autoversion.search_tags true end local do |local| local.vendor_path 'vendor' local.cookbook_path 'cookbooks' local.staging_directory '/var/chef' end cookbook do |cookbook| cookbook.path = '.' cookbook.berkshelf_config = ::File.join(ENV['HOME'], '.berkshelf/config.json') cookbook.add_source 'https://supermarket.chef.io' end aws.region 'us-east-1' profile :default do |profile| profile.log_level :info profile.vagrant do |vagrant| vagrant.ec2 do |ec2| ec2.provider :aws ec2.box 'dummy' ec2.box_url 'https://github.com/mitchellh/vagrant-aws/raw/master/dummy.box' ec2.instance_type 't2.micro' ec2.public_ip true end vagrant.local do |local| local.provider :virtualbox local.box 'ubuntu-14.04-x86_64' local.box_url 'https://cloud-images.ubuntu.com/vagrant/trusty/'\ 'current/trusty-server-cloudimg-amd64-vagrant-disk1.box' local.memory 1024 local.cpus 2 end end profile.packer do |packer| packer.build :default do |build| build.type 'amazon-ebs' build.instance_type 'c3.large' build.ssh_username 'ubuntu' build.ami_virtualization_type 'hvm' build.ami_name [Config.build_name, Config.version, Config.build_number].reject(&:nil?).join('-') build.ami_description Config.description end end end profile(:bake).extends :default cleaner do |cleaner| cleaner.commit false cleaner.force false cleaner.filters {} cleaner.sort_by 'creation_date' cleaner.keep 5 cleaner.limits do |limits| limits.images 24 limits.launch_configs 48 limits.snapshots 24 limits.volumes 8 end end generator.gemfile.vagrant do |vagrant| vagrant.install true vagrant.version 'v1.7.4' end generator.project :jetty do |jetty| jetty.berksfile :rm jetty.buildfile :create jetty.gemfile :create jetty.gitignore :create jetty.rubocop :create jetty.packerfile :rm jetty.vagrantfile :rm jetty.thorfile :rm jetty.cookbook :rm end ## Ensure that attributes[:vendor] is a populated vendor {} end end end
module RightData class FileSystemItem attr_reader :relativePath attr_reader :parent attr_reader :ignore_children attr_reader :duplicate_children attr_accessor :duplicates attr_accessor :ignorable def initialize path, args if args[:parent] @relativePath = File.basename(path) @parent = args[:parent] else @relativePath = path @parent = nil end @ignorable = false @duplicates = [] # for this node @duplicate_children = 0 # counts for children @ignore_children = 0 self end def files return 0 if leaf? && File.directory?(fullPath) return 1 if leaf? return children.map {|n| n.files}.inject {|sum, n| sum + n } end def ignore_files return 0 if leaf? && File.directory?(fullPath) return ignorable? ? 1 : 0 if leaf? return children.map {|n| n.ignore_files}.inject {|sum, n| sum + n } end def duplicate_files return 0 if leaf? && File.directory?(fullPath) return duplicate? ? 1 : 0 if leaf? return children.map {|n| n.duplicate_files}.inject {|sum, n| sum + n } end def basename; @relativePath; end def self.rootItem @rootItem ||= self.new '/', :parent => nil end def children unless @children if File.directory?(fullPath) and File.readable?(fullPath) @children = Dir.entries(fullPath).select { |path| path != '.' and path != '..' }.map { |path| FileSystemItem.new path, :parent => self } else @children = nil end end @children end def path; fullPath; end def fullPath @parent ? File.join(@parent.fullPath, @relativePath) : @relativePath end def childAtIndex n children[n] end def numberOfChildren children == nil ? -1 : children.size end def children?; !children.nil? && !children.empty?; end def duplicate? if leaf? !duplicates.empty? else # Dup if all ignored / dup children ((@ignore_children + @duplicate_children) == numberOfChildren) end end def ignorable?; ignorable; end def increment_ignorable_children @ignore_children += 1 update_duplicate_ignorable_status end def update_duplicate_ignorable_status parent.increment_duplicate_children if((@ignore_children + @duplicate_children) == numberOfChildren) end def increment_duplicate_children @duplicate_children += 1 update_duplicate_ignorable_status end def leaf?; !children?; end def traverse(&block) # Allow proc to decide if we traverse if block.call(self) && children? children.each { |c| c.traverse(&block) } end end def other_children children.size - ignore_children - duplicate_children end def to_param; to_s; end def to_s "<Tree :path => #{self.path}, :files => #{self.files}>" end # Inspect the nodes: def report(pre="") pre += " " if !pre.empty? self.traverse do |n| # Is this a leaf (e.g. a file)? if n.leaf? if(File.directory?(n.path)) # Prune empty dirs! puts "#{pre}'#{n.path.gsub(/'/,"\\'")}' # Empty dir" # Remove the dups/igns! else msg = nil msg = "# dup(#{n.duplicates.count})" if n.duplicate? msg = "# ign" if n.ignorable? if msg puts "#{pre}'#{n.path.gsub(/'/,"\\'")}' #{msg}" # Remove the dups/igns! else puts "# #{n.path} unique" end end false # Don't traverse deeper! else if n.duplicate_children + n.ignore_children == n.children.size puts "#{pre}'#{n.path.gsub(/'/,"\\'")}' # #{n.duplicate_children} dups / #{n.ignore_children} ignores" false # Don't traverse deeper! elsif n.children.size == 0 puts "#{pre}'#{n.path.gsub(/'/,"\\'")}' # Empty... " false else puts "# #{n.path} # Not #{n.duplicate_children} dup/ #{n.ignore_children} ign / #{n.other_children} other " true end end end puts "# #{self.ignore_files} ignores, #{self.duplicate_files} dups of #{self.files} files" end end end Fixing escapes. module RightData class FileSystemItem attr_reader :relativePath attr_reader :parent attr_reader :ignore_children attr_reader :duplicate_children attr_accessor :duplicates attr_accessor :ignorable def initialize path, args if args[:parent] @relativePath = File.basename(path) @parent = args[:parent] else @relativePath = path @parent = nil end @ignorable = false @duplicates = [] # for this node @duplicate_children = 0 # counts for children @ignore_children = 0 self end def files return 0 if leaf? && File.directory?(fullPath) return 1 if leaf? return children.map {|n| n.files}.inject {|sum, n| sum + n } end def ignore_files return 0 if leaf? && File.directory?(fullPath) return ignorable? ? 1 : 0 if leaf? return children.map {|n| n.ignore_files}.inject {|sum, n| sum + n } end def duplicate_files return 0 if leaf? && File.directory?(fullPath) return duplicate? ? 1 : 0 if leaf? return children.map {|n| n.duplicate_files}.inject {|sum, n| sum + n } end def basename; @relativePath; end def self.rootItem @rootItem ||= self.new '/', :parent => nil end def children unless @children if File.directory?(fullPath) and File.readable?(fullPath) @children = Dir.entries(fullPath).select { |path| path != '.' and path != '..' }.map { |path| FileSystemItem.new path, :parent => self } else @children = nil end end @children end def path; fullPath; end def fullPath @parent ? File.join(@parent.fullPath, @relativePath) : @relativePath end def childAtIndex n children[n] end def numberOfChildren children == nil ? -1 : children.size end def children?; !children.nil? && !children.empty?; end def duplicate? if leaf? !duplicates.empty? else # Dup if all ignored / dup children ((@ignore_children + @duplicate_children) == numberOfChildren) end end def ignorable?; ignorable; end def increment_ignorable_children @ignore_children += 1 update_duplicate_ignorable_status end def update_duplicate_ignorable_status parent.increment_duplicate_children if((@ignore_children + @duplicate_children) == numberOfChildren) end def increment_duplicate_children @duplicate_children += 1 update_duplicate_ignorable_status end def leaf?; !children?; end def traverse(&block) # Allow proc to decide if we traverse if block.call(self) && children? children.each { |c| c.traverse(&block) } end end def other_children children.size - ignore_children - duplicate_children end def to_param; to_s; end def to_s "<Tree :path => #{self.path}, :files => #{self.files}>" end # Inspect the nodes: def report(pre="") pre += " " if !pre.empty? self.traverse do |n| # Is this a leaf (e.g. a file)? if n.leaf? if(File.directory?(n.path)) # Prune empty dirs! puts "#{pre}'#{n.path.gsub(/'/,"\\\\'")}' # Empty dir" # Remove the dups/igns! else msg = nil msg = "# dup(#{n.duplicates.count})" if n.duplicate? msg = "# ign" if n.ignorable? if msg puts "#{pre}'#{n.path.gsub(/'/,"\\\\'")}' #{msg}" # Remove the dups/igns! else puts "# #{n.path} unique" end end false # Don't traverse deeper! else if n.duplicate_children + n.ignore_children == n.children.size puts "#{pre}'#{n.path.gsub(/'/,"\\\\'")}' # #{n.duplicate_children} dups / #{n.ignore_children} ignores" false # Don't traverse deeper! elsif n.children.size == 0 puts "#{pre}'#{n.path.gsub(/'/,"\\\\'")}' # Empty... " false else puts "# #{n.path} # Not #{n.duplicate_children} dup/ #{n.ignore_children} ign / #{n.other_children} other " true end end end puts "# #{self.ignore_files} ignores, #{self.duplicate_files} dups of #{self.files} files" end end end
Create typo.rb module BuntoImport module Importers class Typo < Importer # This SQL *should* work for both MySQL and PostgreSQL. SQL = <<-EOS SELECT c.id id, c.title title, c.permalink slug, c.body body, c.extended extended, c.published_at date, c.state state, c.keywords keywords, COALESCE(tf.name, 'html') filter FROM contents c LEFT OUTER JOIN text_filters tf ON c.text_filter_id = tf.id EOS def self.require_deps BuntoImport.require_with_fallback(%w[ rubygems sequel fileutils safe_yaml ]) end def self.specify_options(c) c.option 'server', '--server TYPE', 'Server type ("mysql" or "postgres")' c.option 'dbname', '--dbname DB', 'Database name' c.option 'user', '--user USER', 'Database user name' c.option 'password', '--password PW', "Database user's password (default: '')" c.option 'host', '--host HOST', 'Database host name' end def self.process(options) server = options.fetch('server') dbname = options.fetch('dbname') user = options.fetch('user') pass = options.fetch('password', '') host = options.fetch('host', "localhost") FileUtils.mkdir_p '_posts' case server.intern when :postgres db = Sequel.postgres(dbname, :user => user, :password => pass, :host => host, :encoding => 'utf8') when :mysql db = Sequel.mysql(dbname, :user => user, :password => pass, :host => host, :encoding => 'utf8') else raise "Unknown database server '#{server}'" end db[SQL].each do |post| next unless post[:state] =~ /published/i if post[:slug] == nil post[:slug] = "no slug" end if post[:extended] post[:body] << "\n<!-- more -->\n" post[:body] << post[:extended] end name = [ sprintf("%.04d", post[:date].year), sprintf("%.02d", post[:date].month), sprintf("%.02d", post[:date].day), post[:slug].strip ].join('-') # Can have more than one text filter in this field, but we just want # the first one for this. name += '.' + post[:filter].split(' ')[0] File.open("_posts/#{name}", 'w') do |f| f.puts({ 'layout' => 'post', 'title' => (post[:title] and post[:title].to_s.force_encoding('UTF-8')), 'tags' => (post[:keywords] and post[:keywords].to_s.force_encoding('UTF-8')), 'typo_id' => post[:id] }.delete_if { |k, v| v.nil? || v == '' }.to_yaml) f.puts '---' f.puts post[:body].delete("\r") end end end end end end
namespace :db do task :backup do ask(:backup_name, "snapshots") on roles(:app) do sudo "backup perform --trigger #{fetch(:backup_name)}" end end desc "Seed database" task :seed do on primary(fetch(:migration_role)) do within release_path do with rails_env: fetch(:env), rack_env: fetch(:env) do execute :rake, "db:seed" end end end end after "deploy:migrate", "db:seed" end Update database.rake namespace :db do task :backup do ask(:backup_name, "snapshots") on roles(:app) do sudo "backup perform --trigger #{fetch(:backup_name)}" end end desc "Seed database" task :seed do on primary(fetch(:migration_role, :db)) do within release_path do with rails_env: fetch(:env), rack_env: fetch(:env) do execute :rake, "db:seed" end end end end after "deploy:migrate", "db:seed" end
def getGitInfos(commit) rawCommitDate = capture(:git, "log -1 --pretty=tformat:'{%ci}' --no-color --date=local #{commit}").slice(/\{(.+)\}/,1).sub(/\s/, 'T').sub(/\s/, '') abbrevCommit = capture(:git, "rev-list --max-count=1 --abbrev-commit #{commit}") fullCommit = capture(:git, "rev-list --max-count=1 --no-abbrev-commit #{commit}") version = capture(:git, "describe --tag #{commit}") if version.empty? version = abbrevCommit end deployDate = Time.strptime(release_timestamp, "%Y%m%d%H%M%S").in_time_zone commitDate = Time.strptime(rawCommitDate, "%Y-%m-%dT%H:%M:%S%z").in_time_zone return { 'version' => version, 'abbrev_commit' => abbrevCommit, 'full_commit' => fullCommit, 'commit_date' => commitDate.strftime('%FT%T%z'), 'commit_timestamp' => commitDate.strftime('%s'), 'deploy_date' => deployDate.strftime('%FT%T%z'), 'deploy_timestamp' => deployDate.strftime('%s'), } end def formatGitInfos(infos, format) case format when "yml" # TODO find option to force quoting to prevent abbrev_commit to be read as float in YAML # return YAML.dump(infos) return <<-YAML --- version: '#{infos['version']}' abbrev_commit: '#{infos['abbrev_commit']}' full_commit: '#{infos['full_commit']}' commit_date: '#{infos['commit_date']}' commit_timestamp: '#{infos['commit_timestamp']}' deploy_date: '#{infos['deploy_date']}' deploy_timestamp: '#{infos['deploy_timestamp']}' YAML when "xml" builder = Nokogiri::XML::Builder.new do |xml| xml.send("#{fetch(:gitinfos_section)}") do infos.each do |key, value| xml.send(key, value) end end end return builder.to_xml when "ini" ini = IniFile.new ini["#{fetch(:gitinfos_section)}"] = infos return ini.to_s else set :gitinfos_format, "json" return JSON.pretty_generate(infos)+"\n" end end namespace :gitinfos do task :set_version_infos do on release_roles :all do within repo_path do with fetch(:git_environmental_variables) do infos = formatGitInfos(getGitInfos(fetch(:branch)), fetch(:gitinfos_format)) upload! StringIO.new(infos), "#{release_path}/#{fetch(:gitinfos_file)}.#{fetch(:gitinfos_format)}" end end end end end fix git describe return an error def getGitInfos(commit) rawCommitDate = capture(:git, "log -1 --pretty=tformat:'{%ci}' --no-color --date=local #{commit}").slice(/\{(.+)\}/,1).sub(/\s/, 'T').sub(/\s/, '') abbrevCommit = capture(:git, "rev-list --max-count=1 --abbrev-commit #{commit}") fullCommit = capture(:git, "rev-list --max-count=1 --no-abbrev-commit #{commit}") begin version = capture(:git, "describe --tag #{commit}") rescue SSHKit::Runner::ExecuteError => e version = abbrevCommit end if version.empty? version = abbrevCommit end deployDate = Time.strptime(release_timestamp, "%Y%m%d%H%M%S").in_time_zone commitDate = Time.strptime(rawCommitDate, "%Y-%m-%dT%H:%M:%S%z").in_time_zone return { 'version' => version, 'abbrev_commit' => abbrevCommit, 'full_commit' => fullCommit, 'commit_date' => commitDate.strftime('%FT%T%z'), 'commit_timestamp' => commitDate.strftime('%s'), 'deploy_date' => deployDate.strftime('%FT%T%z'), 'deploy_timestamp' => deployDate.strftime('%s'), } end def formatGitInfos(infos, format) case format when "yml" # TODO find option to force quoting to prevent abbrev_commit to be read as float in YAML # return YAML.dump(infos) return <<-YAML --- version: '#{infos['version']}' abbrev_commit: '#{infos['abbrev_commit']}' full_commit: '#{infos['full_commit']}' commit_date: '#{infos['commit_date']}' commit_timestamp: '#{infos['commit_timestamp']}' deploy_date: '#{infos['deploy_date']}' deploy_timestamp: '#{infos['deploy_timestamp']}' YAML when "xml" builder = Nokogiri::XML::Builder.new do |xml| xml.send("#{fetch(:gitinfos_section)}") do infos.each do |key, value| xml.send(key, value) end end end return builder.to_xml when "ini" ini = IniFile.new ini["#{fetch(:gitinfos_section)}"] = infos return ini.to_s else set :gitinfos_format, "json" return JSON.pretty_generate(infos)+"\n" end end namespace :gitinfos do task :set_version_infos do on release_roles :all do within repo_path do with fetch(:git_environmental_variables) do infos = formatGitInfos(getGitInfos(fetch(:branch)), fetch(:gitinfos_format)) upload! StringIO.new(infos), "#{release_path}/#{fetch(:gitinfos_file)}.#{fetch(:gitinfos_format)}" end end end end end
# encoding: utf-8 module CartoDB module Visualization class RedisVizjsonCache # This needs to be changed whenever there're changes in the code that require invalidation of old keys VERSION = '1'.freeze def initialize(redis_cache = $tables_metadata, vizjson_version = 2) @redis = redis_cache @vizjson_version = vizjson_version end def cached(visualization_id, https_flag = false, vizjson_version = @vizjson_version) key = key(visualization_id, https_flag, vizjson_version) value = redis.get(key) if value.present? JSON.parse(value, symbolize_names: true) else result = yield serialized = JSON.generate(result) redis.setex(key, 24.hours.to_i, serialized) result end end def invalidate(visualization_id) purge_ids([visualization_id]) end def key(visualization_id, https_flag = false, vizjson_version = @vizjson_version) "visualization:#{visualization_id}:vizjson#{VIZJSON_VERSION_KEY[vizjson_version]}:#{VERSION}:#{https_flag ? 'https' : 'http'}" end def purge(vizs) purge_ids(vizs.map(&:id)) end private def purge_ids(ids) return unless ids.count > 0 keys = VIZJSON_VERSION_KEY.keys.map { |vizjson_version| ids.map { |id| [key(id, false, vizjson_version), key(id, true, vizjson_version)] }.flatten }.flatten redis.del keys end # Needs to know every version because of invalidation VIZJSON_VERSION_KEY = { 2 => '', # VizJSON v2 3 => '3', # VizJSON v3 '3n' => '3n', # VizJSON v3 forcing named maps (needed for embeds, see #7093) '3a' => '3a' # VizJSON v3 forcing anonymoys maps (needed for editor, see #7150) }.freeze def redis @redis end end end end Make vizjson cache depend on domain # encoding: utf-8 module CartoDB module Visualization class RedisVizjsonCache # This needs to be changed whenever there're changes in the code that require invalidation of old keys VERSION = '1'.freeze def initialize(redis_cache = $tables_metadata, vizjson_version = 2) @redis = redis_cache @vizjson_version = vizjson_version end def cached(visualization_id, https_flag = false, vizjson_version = @vizjson_version) key = key(visualization_id, https_flag, vizjson_version) value = redis.get(key) if value.present? JSON.parse(value, symbolize_names: true) else result = yield serialized = JSON.generate(result) redis.setex(key, 24.hours.to_i, serialized) result end end def invalidate(visualization_id) purge_ids([visualization_id]) end def key(visualization_id, https_flag = false, vizjson_version = @vizjson_version) "visualization:#{visualization_id}:vizjson#{VIZJSON_VERSION_KEY[vizjson_version]}:#{VERSION}:" \ "#{https_flag ? 'https' : 'http'}:#{CartoDB.session_domain}" end def purge(vizs) purge_ids(vizs.map(&:id)) end private def purge_ids(ids) return unless ids.count > 0 keys = VIZJSON_VERSION_KEY.keys.map { |vizjson_version| ids.map { |id| [key(id, false, vizjson_version), key(id, true, vizjson_version)] }.flatten }.flatten redis.del keys end # Needs to know every version because of invalidation VIZJSON_VERSION_KEY = { 2 => '', # VizJSON v2 3 => '3', # VizJSON v3 '3n' => '3n', # VizJSON v3 forcing named maps (needed for embeds, see #7093) '3a' => '3a' # VizJSON v3 forcing anonymoys maps (needed for editor, see #7150) }.freeze def redis @redis end end end end
require 'caruby/database/fetched_matcher' module CaRuby class Database # A LazyLoader fetches an association from the database on demand. class LazyLoader < Proc # Creates a new LazyLoader which calls the loader block on the subject. # # @yield [subject, attribute] fetches the given subject attribute value from the database # @yieldparam [Resource] subject the domain object whose attribute is to be loaded # @yieldparam [Symbol] attribute the domain attribute to load def initialize(&loader) super { |sbj, attr| load(sbj, attr, &loader) } # the fetch result matcher @matcher = FetchedMatcher.new @enabled = true end # Disables this lazy loader. If the loader is already disabled, then this method is a no-op. # Otherwise, if a block is given, then the lazy loader is reenabled after the block is executed. # # @yield the block to call while the loader is disabled # @return the result of calling the block if a block is given, nil otherwise def disable reenable = set_disabled return unless block_given? begin yield ensure set_enabled if reenable end end alias :suspend :disable # Enables this lazy loader. If the loader is already enabled, then this method is a no-op. # Otherwise, if a block is given, then the lazy loader is redisabled after the block is executed. # # @yield the block to call while the loader is enabled # @return the result of calling the block if a block is given, nil otherwise def enable redisable = set_enabled return unless block_given? begin yield ensure set_disabled if redisable end end alias :resume :enable # @return [Boolean] whether this loader is enabled def enabled? @enabled end # @return [Boolean] whether this loader is disabled def disabled? not @enabled end private # Disables this loader. # # @return [Boolean] true if this loader was previously enabled, false otherwise def set_disabled enabled? and (@enabled = false; true) end # Enables this loader. # # @return [Boolean] true if this loader was previously disabled, false otherwise def set_enabled disabled? and (@enabled = true) end # @param [Resource] subject the domain object whose attribute is to be loaded # @param [Symbol] the domain attribute to load # @yield (see #initialize) # @yieldparam (see #initialize) # @return the attribute value loaded from the database # @raise [RuntimeError] if this loader is disabled def load(subject, attribute) if disabled? then raise RuntimeError.new("#{subject.qp} lazy load called on disabled loader") end logger.debug { "Lazy-loading #{subject.qp} #{attribute}..." } # the current value oldval = subject.send(attribute) # load the fetched value fetched = yield(subject, attribute) # nothing to merge if nothing fetched return oldval if fetched.nil_or_empty? # merge the fetched into the attribute logger.debug { "Merging #{subject.qp} fetched #{attribute} value #{fetched.qp}#{' into ' + oldval.qp if oldval}..." } matches = @matcher.match(fetched.to_enum, oldval.to_enum) subject.merge_attribute(attribute, fetched, matches) end end end end Make load method rather than proc. require 'caruby/database/fetched_matcher' module CaRuby class Database # A LazyLoader fetches an association from the database on demand. class LazyLoader # Creates a new LazyLoader which calls the loader block on the subject. # # @yield [subject, attribute] fetches the given subject attribute value from the database # @yieldparam [Resource] subject the domain object whose attribute is to be loaded # @yieldparam [Symbol] attribute the domain attribute to load def initialize(&loader) @loader = loader # the fetch result matcher @matcher = FetchedMatcher.new @enabled = true end # @param [Resource] subject the domain object whose attribute is to be loaded # @param [Symbol] the domain attribute to load # @yield (see #initialize) # @yieldparam (see #initialize) # @return the attribute value loaded from the database # @raise [RuntimeError] if this loader is disabled def load(subject, attribute) if disabled? then raise RuntimeError.new("#{subject.qp} lazy load called on disabled loader") end logger.debug { "Lazy-loading #{subject.qp} #{attribute}..." } # the current value oldval = subject.send(attribute) # load the fetched value fetched = @loader.call(subject, attribute) # nothing to merge if nothing fetched return oldval if fetched.nil_or_empty? # merge the fetched into the attribute logger.debug { "Merging #{subject.qp} fetched #{attribute} value #{fetched.qp}#{' into ' + oldval.qp if oldval}..." } matches = @matcher.match(fetched.to_enum, oldval.to_enum) subject.merge_attribute(attribute, fetched, matches) end # Disables this lazy loader. If the loader is already disabled, then this method is a no-op. # Otherwise, if a block is given, then the lazy loader is reenabled after the block is executed. # # @yield the block to call while the loader is disabled # @return the result of calling the block if a block is given, nil otherwise def disable reenable = set_disabled return unless block_given? begin yield ensure set_enabled if reenable end end alias :suspend :disable # Enables this lazy loader. If the loader is already enabled, then this method is a no-op. # Otherwise, if a block is given, then the lazy loader is redisabled after the block is executed. # # @yield the block to call while the loader is enabled # @return the result of calling the block if a block is given, nil otherwise def enable redisable = set_enabled return unless block_given? begin yield ensure set_disabled if redisable end end alias :resume :enable # @return [Boolean] whether this loader is enabled def enabled? @enabled end # @return [Boolean] whether this loader is disabled def disabled? not @enabled end private # Disables this loader. # # @return [Boolean] true if this loader was previously enabled, false otherwise def set_disabled enabled? and (@enabled = false; true) end # Enables this loader. # # @return [Boolean] true if this loader was previously disabled, false otherwise def set_enabled disabled? and (@enabled = true) end end end end
class Cassandra class DynamicComposite < Composite attr_accessor :types def initialize(*parts) return if parts.empty? options = {} if parts.last.is_a?(Hash) options = parts.pop end @column_slice = options[:slice] raise ArgumentError if @column_slice != nil && ![:before, :after].include?(@column_slice) if parts.length == 1 && parts[0].instance_of?(self.class) @column_slice = parts[0].column_slice @parts = parts[0].parts @types = parts[0].types elsif parts.length == 1 && parts[0].instance_of?(String) && @column_slice.nil? && try_packed_composite(parts[0]) @hash = parts[0].hash else @types, @parts = parts.transpose end end def pack packed_parts = @parts.map do |part| [part.length].pack('n') + part + "\x00" end if @column_slice part = @parts[-1] packed_parts[-1] = [part.length].pack('n') + part + slice_end_of_component end packed_types = @types.map do |type| if type.length == 1 [0x8000 | type.ord].pack('n') else [type.length].pack('n') + type end end return packed_types.zip(packed_parts).flatten.join('') end def fast_unpack(packed_string) result = try_packed_composite(packed_string) raise ArgumentError.new("Invalid DynamicComposite column") if !result @hash = packed_string.hash end private def try_packed_composite(packed_string) types = [] parts = [] end_of_component = nil offset = 0 read_bytes = proc do |length| return false if offset + length > packed_string.length out = packed_string.slice(offset, length) offset += length out end while offset < packed_string.length header = read_bytes.call(2).unpack('n')[0] is_alias = header & 0x8000 != 0 if is_alias alias_char = (header & 0xFF).chr types << alias_char else length = header return false if length.nil? || length + offset > packed_string.length type = read_bytes.call(length) types << type end length = read_bytes.call(2).unpack('n')[0] return false if length.nil? || length + offset > packed_string.length parts << read_bytes.call(length) end_of_component = read_bytes.call(1) if offset < packed_string.length return false if end_of_component != "\x00" end end @column_slice = :after if end_of_component == "\x01" @column_slice = :before if end_of_component == "\xFF" @types = types @parts = parts @hash = packed_string.hash return true end end end Fix for lacking String#ord on Ruby 1.8. This should work on both. class Cassandra class DynamicComposite < Composite attr_accessor :types def initialize(*parts) return if parts.empty? options = {} if parts.last.is_a?(Hash) options = parts.pop end @column_slice = options[:slice] raise ArgumentError if @column_slice != nil && ![:before, :after].include?(@column_slice) if parts.length == 1 && parts[0].instance_of?(self.class) @column_slice = parts[0].column_slice @parts = parts[0].parts @types = parts[0].types elsif parts.length == 1 && parts[0].instance_of?(String) && @column_slice.nil? && try_packed_composite(parts[0]) @hash = parts[0].hash else @types, @parts = parts.transpose end end def pack packed_parts = @parts.map do |part| [part.length].pack('n') + part + "\x00" end if @column_slice part = @parts[-1] packed_parts[-1] = [part.length].pack('n') + part + slice_end_of_component end packed_types = @types.map do |type| if type.length == 1 [0x8000 | type[0].ord].pack('n') else [type.length].pack('n') + type end end return packed_types.zip(packed_parts).flatten.join('') end def fast_unpack(packed_string) result = try_packed_composite(packed_string) raise ArgumentError.new("Invalid DynamicComposite column") if !result @hash = packed_string.hash end private def try_packed_composite(packed_string) types = [] parts = [] end_of_component = nil offset = 0 read_bytes = proc do |length| return false if offset + length > packed_string.length out = packed_string.slice(offset, length) offset += length out end while offset < packed_string.length header = read_bytes.call(2).unpack('n')[0] is_alias = header & 0x8000 != 0 if is_alias alias_char = (header & 0xFF).chr types << alias_char else length = header return false if length.nil? || length + offset > packed_string.length type = read_bytes.call(length) types << type end length = read_bytes.call(2).unpack('n')[0] return false if length.nil? || length + offset > packed_string.length parts << read_bytes.call(length) end_of_component = read_bytes.call(1) if offset < packed_string.length return false if end_of_component != "\x00" end end @column_slice = :after if end_of_component == "\x01" @column_slice = :before if end_of_component == "\xFF" @types = types @parts = parts @hash = packed_string.hash return true end end end
module Celluloid # Tasks with a Thread backend class TaskThread attr_reader :type, :status # Run the given block within a task def initialize(type) @type = type @status = :new @yield = Queue.new @resume = Queue.new actor, mailbox = Thread.current[:actor], Thread.current[:mailbox] raise NotActorError, "can't create tasks outside of actors" unless actor @thread = InternalPool.get do @resume.pop @status = :running Thread.current[:actor] = actor Thread.current[:mailbox] = mailbox Thread.current[:task] = self actor.tasks << self begin yield rescue Task::TerminatedError # Task was explicitly terminated ensure @status = :dead actor.tasks.delete self @yield.push nil end end end # Suspend the current task, changing the status to the given argument def suspend(status) @status = status @yield.push(nil) result = @resume.pop raise result if result.is_a?(Task::TerminatedError) @status = :running result end # Resume a suspended task, giving it a value to return if needed def resume(value = nil) raise DeadTaskError, "cannot resume a dead task" unless @thread.alive? @resume.push(value) @yield.pop nil rescue ThreadError raise DeadTaskError, "cannot resume a dead task" end # Terminate this task def terminate resume Task::TerminatedError.new("task was terminated") if @thread.alive? end # Is the current task still running? def running?; @status != :dead; end # Nicer string inspect for tasks def inspect "<Celluloid::Task:0x#{object_id.to_s(16)} @type=#{@type.inspect}, @status=#{@status.inspect}>" end end end Use a mutex/condition instead of a queue module Celluloid # Tasks with a Thread backend class TaskThread attr_reader :type, :status # Run the given block within a task def initialize(type) @type = type @status = :new @resume_queue = Queue.new @yield_mutex = Mutex.new @yield_cond = ConditionVariable.new actor, mailbox = Thread.current[:actor], Thread.current[:mailbox] raise NotActorError, "can't create tasks outside of actors" unless actor @thread = InternalPool.get do begin value = @resume_queue.pop raise value if value.is_a?(Task::TerminatedError) @status = :running Thread.current[:actor] = actor Thread.current[:mailbox] = mailbox Thread.current[:task] = self actor.tasks << self yield rescue Task::TerminatedError # Task was explicitly terminated ensure @status = :dead actor.tasks.delete self @yield_cond.signal end end end # Suspend the current task, changing the status to the given argument def suspend(status) @status = status @yield_cond.signal value = @resume_queue.pop raise value if value.is_a?(Task::TerminatedError) @status = :running value end # Resume a suspended task, giving it a value to return if needed def resume(value = nil) raise DeadTaskError, "cannot resume a dead task" unless @thread.alive? @yield_mutex.synchronize do @resume_queue.push(value) @yield_cond.wait(@yield_mutex) end nil rescue ThreadError raise DeadTaskError, "cannot resume a dead task" end # Terminate this task def terminate resume Task::TerminatedError.new("task was terminated") if @thread.alive? end # Is the current task still running? def running?; @status != :dead; end # Nicer string inspect for tasks def inspect "<Celluloid::Task:0x#{object_id.to_s(16)} @type=#{@type.inspect}, @status=#{@status.inspect}>" end end end
module CelluloidBenchmark VERSION = "0.3.0" end Rev version module CelluloidBenchmark VERSION = "0.3.5" end
# Copyright (C) 2013-2017 Kouhei Sutou <kou@clear-code.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA require "nkf" require "nokogiri" module ChupaText module Decomposers class HTML < Decomposer registry.register("html", self) TARGET_EXTENSIONS = ["htm", "html", "xhtml"] TARGET_MIME_TYPES = [ "text/html", "application/xhtml+xml", ] def target?(data) TARGET_EXTENSIONS.include?(data.extension) or TARGET_MIME_TYPES.include?(data.mime_type) end def decompose(data) html = data.body doc = Nokogiri::HTML.parse(html, nil, guess_encoding(html)) body_element = (doc % "body") if body_element body = body_element.text.gsub(/^\s+|\s+$/, '') else body = "" end decomposed_data = TextData.new(body, :source_data => data) attributes = decomposed_data.attributes title_element = (doc % "head/title") attributes.title = title_element.text if title_element encoding = doc.encoding attributes.encoding = encoding if encoding yield(decomposed_data) end private def guess_encoding(text) unless text.encoding.ascii_compatible? return text.encoding.name end case text when /\A<\?xml.+?encoding=(['"])([a-zA-Z0-9_-]+)\1/ $2 when /<meta\s[^>]* http-equiv=(['"])content-type\1\s+ content=(['"])(.+?)\2/imx # " content_type = $3 _, parameters = content_type.split(/;\s*/, 2) encoding = nil if parameters and /\bcharset=([a-zA-Z0-9_-]+)/i =~ parameters encoding = normalize_charset($1) end encoding when /<meta\s[^>]*charset=(['"])(.+?)\1/imx # " charset = $2 normalize_charset(charset) else if text.encoding != Encoding::ASCII_8BIT and text.valid_encoding? text.encoding.to_s else guess_encoding_nkf(text) end end end def normalize_charset(charset) case charset when /\Ax-sjis\z/i normalize_charset("Shift_JIS") when /\Ashift[_-]jis\z/i "Windows-31J" else charset end end def guess_encoding_nkf(text) NKF.guess(text).name end end end end Scrub invalid characters # Copyright (C) 2013-2017 Kouhei Sutou <kou@clear-code.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA require "nkf" require "nokogiri" module ChupaText module Decomposers class HTML < Decomposer registry.register("html", self) TARGET_EXTENSIONS = ["htm", "html", "xhtml"] TARGET_MIME_TYPES = [ "text/html", "application/xhtml+xml", ] def target?(data) TARGET_EXTENSIONS.include?(data.extension) or TARGET_MIME_TYPES.include?(data.mime_type) end def decompose(data) html = data.body doc = Nokogiri::HTML.parse(html, nil, guess_encoding(html)) body_element = (doc % "body") if body_element body = body_element.text.scrub.gsub(/^\s+|\s+$/, '') else body = "" end decomposed_data = TextData.new(body, :source_data => data) attributes = decomposed_data.attributes title_element = (doc % "head/title") attributes.title = title_element.text if title_element encoding = doc.encoding attributes.encoding = encoding if encoding yield(decomposed_data) end private def guess_encoding(text) unless text.encoding.ascii_compatible? return text.encoding.name end case text when /\A<\?xml.+?encoding=(['"])([a-zA-Z0-9_-]+)\1/ $2 when /<meta\s[^>]* http-equiv=(['"])content-type\1\s+ content=(['"])(.+?)\2/imx # " content_type = $3 _, parameters = content_type.split(/;\s*/, 2) encoding = nil if parameters and /\bcharset=([a-zA-Z0-9_-]+)/i =~ parameters encoding = normalize_charset($1) end encoding when /<meta\s[^>]*charset=(['"])(.+?)\1/imx # " charset = $2 normalize_charset(charset) else if text.encoding != Encoding::ASCII_8BIT and text.valid_encoding? text.encoding.to_s else guess_encoding_nkf(text) end end end def normalize_charset(charset) case charset when /\Ax-sjis\z/i normalize_charset("Shift_JIS") when /\Ashift[_-]jis\z/i "Windows-31J" else charset end end def guess_encoding_nkf(text) NKF.guess(text).name end end end end
# # NXAPI implementation of VXLAN_VTEP class # # November 2015, Deepak Cherian # # Copyright (c) 2015 Cisco and/or its affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative 'node_util' module Cisco # node_utils class for vxlan_vtep class VxlanVtep < NodeUtil attr_reader :name def initialize(name, instantiate=true) fail TypeError unless name.is_a?(String) fail ArgumentError unless name.length > 0 @name = name.downcase create if instantiate end def self.vteps hash = {} return hash unless feature_enabled vtep_list = config_get('vxlan_vtep', 'all_interfaces') return hash if vtep_list.nil? vtep_list.each do |id| id = id.downcase hash[id] = VxlanVtep.new(id, false) end hash end def self.feature_enabled config_get('vxlan', 'feature') rescue Cisco::CliError => e # cmd will syntax when feature is not enabled. raise unless e.clierror =~ /Syntax error/ return false end def self.enable(state='') # vdc only supported on n7k currently. vdc_name = config_get('limit_resource', 'vdc') config_set('limit_resource', 'vxlan', vdc_name) unless vdc_name.nil? config_set('vxlan', 'feature', state: state) end def create VxlanVtep.enable unless VxlanVtep.feature_enabled # re-use the "interface command ref hooks" config_set('interface', 'create', @name) end def destroy # re-use the "interface command ref hooks" config_set('interface', 'destroy', @name) end def ==(other) name == other.name end ######################################################## # PROPERTIES # ######################################################## def description config_get('interface', 'description', @name) end def description=(desc) fail TypeError unless desc.is_a?(String) if desc.empty? config_set('interface', 'description', @name, 'no', '') else config_set('interface', 'description', @name, '', desc) end end def default_description config_get_default('interface', 'description') end def host_reachability hr = config_get('vxlan_vtep', 'host_reachability', name: @name) hr == 'bgp' ? 'evpn' : hr end def host_reachability=(val) set_args = { name: @name, proto: 'bgp' } if val.to_s == 'flood' && host_reachability == 'evpn' set_args[:state] = 'no' elsif val.to_s == 'evpn' set_args[:state] = '' end config_set('vxlan_vtep', 'host_reachability', set_args) end def default_host_reachability config_get_default('vxlan_vtep', 'host_reachability') end def source_interface config_get('vxlan_vtep', 'source_intf', name: @name) end def source_interface_set(val) fail TypeError unless val.is_a?(String) if val.empty? config_set('vxlan_vtep', 'source_intf', name: @name, state: 'no', lpbk_intf: val) else config_set('vxlan_vtep', 'source_intf', name: @name, state: '', lpbk_intf: val) end end def source_interface=(val) # The source interface can only be changed if the nve # interface is in a shutdown state. noshut = { name: @name, state: 'no' } shut = { name: @name, state: '' } config_set('vxlan_vtep', 'shutdown', shut) unless shutdown source_interface_set(val) config_set('vxlan_vtep', 'shutdown', noshut) if shutdown end def default_source_interface config_get_default('vxlan_vtep', 'source_intf') end def shutdown config_get('vxlan_vtep', 'shutdown', name: @name) end def shutdown=(bool) state = (bool ? '' : 'no') config_set('vxlan_vtep', 'shutdown', name: @name, state: state) end def default_shutdown config_get_default('vxlan_vtep', 'shutdown') end end # Class end # Module Further simplified source_interface # # NXAPI implementation of VXLAN_VTEP class # # November 2015, Deepak Cherian # # Copyright (c) 2015 Cisco and/or its affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative 'node_util' module Cisco # node_utils class for vxlan_vtep class VxlanVtep < NodeUtil attr_reader :name def initialize(name, instantiate=true) fail TypeError unless name.is_a?(String) fail ArgumentError unless name.length > 0 @name = name.downcase create if instantiate end def self.vteps hash = {} return hash unless feature_enabled vtep_list = config_get('vxlan_vtep', 'all_interfaces') return hash if vtep_list.nil? vtep_list.each do |id| id = id.downcase hash[id] = VxlanVtep.new(id, false) end hash end def self.feature_enabled config_get('vxlan', 'feature') rescue Cisco::CliError => e # cmd will syntax when feature is not enabled. raise unless e.clierror =~ /Syntax error/ return false end def self.enable(state='') # vdc only supported on n7k currently. vdc_name = config_get('limit_resource', 'vdc') config_set('limit_resource', 'vxlan', vdc_name) unless vdc_name.nil? config_set('vxlan', 'feature', state: state) end def create VxlanVtep.enable unless VxlanVtep.feature_enabled # re-use the "interface command ref hooks" config_set('interface', 'create', @name) end def destroy # re-use the "interface command ref hooks" config_set('interface', 'destroy', @name) end def ==(other) name == other.name end ######################################################## # PROPERTIES # ######################################################## def description config_get('interface', 'description', @name) end def description=(desc) fail TypeError unless desc.is_a?(String) if desc.empty? config_set('interface', 'description', @name, 'no', '') else config_set('interface', 'description', @name, '', desc) end end def default_description config_get_default('interface', 'description') end def host_reachability hr = config_get('vxlan_vtep', 'host_reachability', name: @name) hr == 'bgp' ? 'evpn' : hr end def host_reachability=(val) set_args = { name: @name, proto: 'bgp' } if val.to_s == 'flood' && host_reachability == 'evpn' set_args[:state] = 'no' elsif val.to_s == 'evpn' set_args[:state] = '' end config_set('vxlan_vtep', 'host_reachability', set_args) end def default_host_reachability config_get_default('vxlan_vtep', 'host_reachability') end def source_interface config_get('vxlan_vtep', 'source_intf', name: @name) end def source_interface_set(val) set_args = { name: @name, lpbk_intf: val } val.empty? ? set_args[:state] = 'no' : set_args[:state] = '' config_set('vxlan_vtep', 'source_intf', set_args) end def source_interface=(val) # The source interface can only be changed if the nve # interface is in a shutdown state. current_state = shutdown self.shutdown = true unless shutdown source_interface_set(val) self.shutdown = current_state end def default_source_interface config_get_default('vxlan_vtep', 'source_intf') end def shutdown config_get('vxlan_vtep', 'shutdown', name: @name) end def shutdown=(bool) state = (bool ? '' : 'no') config_set('vxlan_vtep', 'shutdown', name: @name, state: state) end def default_shutdown config_get_default('vxlan_vtep', 'shutdown') end end # Class end # Module
module Cms module HippoImporter class AboutUs < CorporatePage def hippo_type 'contentauthoringwebsite:Static' end end end end Fix hippo type name on about us class module Cms module HippoImporter class AboutUs < CorporatePage def hippo_type 'contentauthoringwebsite:StaticPage' end end end end
module Rule class Product DEFAULT_RULE = {product_code:"FR1", qty:2, price:3.11} def initialize(rule={}) @rule = DEFAULT_RULE.merge(rule) end def apply(checkout) ft_products = checkout.cart.select(&:product_code).select{|p| p.product_code == @rule.fetch(:product_code)} free_products = ft_products.each_slice(@rule.fetch(:qty)).select{|p| p.size == 2}.count @rule.fetch(:price) * free_products end end end Accommodate more than 2 for 1 module Rule class Product DEFAULT_RULE = {product_code:"FR1", qty:2, price:3.11} def initialize(rule={}) @rule = DEFAULT_RULE.merge(rule) end def apply(checkout) ft_products = checkout.cart.select(&:product_code).select{|p| p.product_code == @rule.fetch(:product_code)} free_products = ft_products.each_slice(@rule.fetch(:qty)).select{|p| p.size == rule.fetch(:qty)}.count @rule.fetch(:price) * free_products end end end
# frozen_string_literal: true require 'cgi' class RedirectURLFilter < HTML::Pipeline::Filter def call doc.search('a').each do |node| url = node.attr('href') next unless url next if url.start_with?('#') # OK: #hoge next if url.match?(%r{\A/[^/]}) # OK: /hoge if GlobalSetting.root_url.present? next if url.start_with?("#{GlobalSetting.root_url}/") # OK: http://podmum-url/hoge next if url.start_with?("//#{GlobalSetting.root_url.sub(/\Ahttps?:/, '')}/") # OK: //podmum-url/hoge end if GlobalSetting.attachment_file_s3? next if url.start_with?(GlobalSetting.attachment_file_s3_host) # OK end node.set_attribute('href', "/redirect?url=#{CGI.escape(url)}") end doc end end refactor RedirectURLFilter#call # frozen_string_literal: true require 'cgi' class RedirectURLFilter < HTML::Pipeline::Filter def call doc.search('a').each do |node| url = node.attr('href') next unless url next if local_link?(url) next if site_link?(url) next if attachment_file_link?(url) node.set_attribute('href', "/redirect?url=#{CGI.escape(url)}") end doc end private def local_link?(url) return true if url.start_with?('#') # ex) #hoge return true if url.match?(%r{\A/[^/]}) # ex) /hoge false end def site_link?(url) return false unless GlobalSetting.root_url.present? return true if url.start_with?("#{GlobalSetting.root_url}/") # ex) http://podmum-url/hoge return true if url.start_with?("//#{GlobalSetting.root_url.sub(/\Ahttps?:/, '')}/") # ex) //podmum-url/hoge false end def attachment_file_link?(url) return false unless GlobalSetting.attachment_file_s3? url.start_with?(GlobalSetting.attachment_file_s3_host) end end
class CountryProfileCliGem::CLI def call puts "Welcome to Country Profile Gem" self.display_menu end def display_menu input = nil until input == "exit" puts "\nPlease, provide a country name or type \'list\' to get all the countries available in the database or type \'exit\'" input = self.get_user_input if input == 'list' list_of_countries = CountryProfileCliGem::Output.country_list puts list_of_countries elsif CountryProfileCliGem::Country.new.find_by_name?(self.reformat_user_input(input)) && CountryProfileCliGem::Country.new.indicators_available?(self.reformat_user_input(input)) ##Output instantiate with a country puts "show country standard indicators" ######TO BE MODIFIED self.display_sub_menu ####PUT A CHECK CONDItioN country exist elsif input == 'exit' input else puts "\nI am not sure what you mean." end end puts "\nSee you soon!" end def display_sub_menu ###REWRITE THIS FUNCTION if countr end def display_sub_menu input = nil @indicator_and_period = {} while input != "exit" puts "\nif you would like to know about historical data for a specific indicator over a certain period of time, enter the number of the indicator, otherwise type \'exit\'" input = gets.strip if input == "exit" input elsif input.to_i.between?(1, 9) @indicator_and_period[:indicator_number] = input.to_i @indicator_and_period[:indicator_period] = self.time_series @indicator_and_period ######THIS MUST CALL A NEW CLASS FOR TIME SERIES # puts "#{@indicator_and_period}" >>> MUST BE DEVELOPPED!!!! else puts "\nI am not sure what you mean." end end # @indicator_and_period = {} end # def menu # input = nil # # while input != "exit" # puts "\nPlease, provide a country name or type \'list\' to get all the countries available in the database or type \'exit\'" # input = gets.strip # input_formatted = self.reformat_input(input) # # if country_available?(input_formatted) # return_value = output_country_info(input_formatted) # # if return_value.class == Hash # self.sub_menu # end # elsif input == "list" # list_countries # elsif input == "exit" # input # else # puts "\nI am not sure what you mean." # end # end # puts "\nSee you soon!" # end # Private def get_user_input gets.strip end # Private def reformat_user_input(initial_input) initial_input.split(" ").collect do |word| new_word = [] word.split("").each_with_index {|char, index| index == 0 ? new_word << char.capitalize : new_word << char } new_word.join("") end input_formatted.join(" ") end def time_series puts "\nPlease, provide the number of years you would like to go back in time. You can go back up to 40 years for certain countries." input = gets.strip.to_i input < 2 || input > 40 ? self.time_series : input end end Redesign the CLI class in line with the NOTES.md indication class CountryProfileCliGem::CLI def initialize puts "I will load the list of countries" # CountryProfileCliGem::Country.load_country_list end def call puts "Welcome to Country Profile Gem" self.display_menu end def display_menu input = nil until input == "exit" puts "\nPlease, provide a country name or type \'list\' to get all the countries available in the database or type \'exit\'" input = self.get_user_input if input == 'list' puts "this is the list of countries" elsif input == 'country name' puts "these are the standard and macro indicators for 2014" self.display_sub_menu elsif input == 'exit' input else puts "\nI am not sure what you mean." end end puts "\nSee you soon!" end def display_sub_menu input = nil until input == "exit" puts "\nif you would like to know about historical data for a specific indicator over a certain period of time, enter the number of the indicator, otherwise type \'exit\'" input = self.get_user_input if input.to_i.between?(1, 9) { :indicator => input.to_i, :time_period => self.time_period } elsif input == "exit" input else puts "\nI am not sure what you mean." end end end # Private def get_user_input gets.strip end # Private def reformat_user_input(initial_input) initial_input.split(" ").collect do |word| new_word = [] word.split("").each_with_index {|char, index| index == 0 ? new_word << char.capitalize : new_word << char } new_word.join("") end input_formatted.join(" ") end def time_period puts "\nHow many years of data would you would like to see? You can go back up to 40 years for certain countries." input = self.get_user_input input.to_i < 2 || input.to_i > 40 ? self.time_period : input end end # def display_sub_menu # input = nil # @indicator_and_period = {} # # while input != "exit" # puts "\nif you would like to know about historical data for a specific indicator over a certain period of time, enter the number of the indicator, otherwise type \'exit\'" # input = gets.strip # # if input == "exit" # input # elsif input.to_i.between?(1, 9) # @indicator_and_period[:indicator_number] = input.to_i # @indicator_and_period[:indicator_period] = self.time_series # @indicator_and_period ######THIS MUST CALL A NEW CLASS FOR TIME SERIES # # puts "#{@indicator_and_period}" >>> MUST BE DEVELOPPED!!!! # else # puts "\nI am not sure what you mean." # end # end # # @indicator_and_period = {} # end # def menu # input = nil # # while input != "exit" # puts "\nPlease, provide a country name or type \'list\' to get all the countries available in the database or type \'exit\'" # input = gets.strip # input_formatted = self.reformat_input(input) # # if country_available?(input_formatted) # return_value = output_country_info(input_formatted) # # if return_value.class == Hash # self.sub_menu # end # elsif input == "list" # list_countries # elsif input == "exit" # input # else # puts "\nI am not sure what you mean." # end # end # puts "\nSee you soon!" # end
require "cucumber/eclipse/steps/version" require 'cucumber/formatter/progress' require 'cucumber/step_definition_light' module Cucumber module Eclipse module Steps class Json < Cucumber::Formatter::Progress include Cucumber::Formatter::Console class StepDefKey < Cucumber::Formatter::StepDefinitionLight attr_accessor :mean_duration, :status end def initialize(runtime, path_or_io, options) @runtime = runtime @io = ensure_io(path_or_io, "usage") @options = options @stepdef_to_match = Hash.new{|h,stepdef_key| h[stepdef_key] = []} end def before_features(features) print_profile_information end def before_step(step) @step = step @start_time = Time.now end def before_step_result(*args) @duration = Time.now - @start_time end def after_step_result(keyword, step_match, multiline_arg, status, exception, source_indent, background, file_colon_line) step_definition = step_match.step_definition unless step_definition.nil? # nil if it's from a scenario outline stepdef_key = StepDefKey.new(step_definition.regexp_source, step_definition.file_colon_line) @stepdef_to_match[stepdef_key] << { :keyword => keyword, :step_match => step_match, :status => status, :file_colon_line => @step.file_colon_line, :duration => @duration } end super end def print_summary(features) add_unused_stepdefs aggregate_info if @options[:dry_run] keys = @stepdef_to_match.keys.sort {|a,b| a.regexp_source <=> b.regexp_source} else keys = @stepdef_to_match.keys.sort {|a,b| a.mean_duration <=> b.mean_duration}.reverse end keys.each do |stepdef_key| print_step_definition(stepdef_key) if @stepdef_to_match[stepdef_key].any? print_steps(stepdef_key) else @io.puts(" " + format_string("NOT MATCHED BY ANY STEPS", :failed)) end end @io.puts super end def print_step_definition(stepdef_key) @io.print format_string(sprintf("%.7f", stepdef_key.mean_duration), :skipped) + " " unless @options[:dry_run] @io.print format_string(stepdef_key.regexp_source, stepdef_key.status) if @options[:source] indent = max_length - stepdef_key.regexp_source.unpack('U*').length line_comment = " # #{stepdef_key.file_colon_line}".indent(indent) @io.print(format_string(line_comment, :comment)) end @io.puts end def print_steps(stepdef_key) @stepdef_to_match[stepdef_key].each do |step| @io.print " " @io.print format_string(sprintf("%.7f", step[:duration]), :skipped) + " " unless @options[:dry_run] @io.print format_step(step[:keyword], step[:step_match], step[:status], nil) if @options[:source] indent = max_length - (step[:keyword].unpack('U*').length + step[:step_match].format_args.unpack('U*').length) line_comment = " # #{step[:file_colon_line]}".indent(indent) @io.print(format_string(line_comment, :comment)) end @io.puts end end def max_length [max_stepdef_length, max_step_length].compact.max end def max_stepdef_length @stepdef_to_match.keys.flatten.map{|key| key.regexp_source.unpack('U*').length}.max end def max_step_length @stepdef_to_match.values.to_a.flatten.map do |step| step[:keyword].unpack('U*').length + step[:step_match].format_args.unpack('U*').length end.max end def aggregate_info @stepdef_to_match.each do |key, steps| if steps.empty? key.status = :skipped key.mean_duration = 0 else key.status = worst_status(steps.map{ |step| step[:status] }) total_duration = steps.inject(0) {|sum, step| step[:duration] + sum} key.mean_duration = total_duration / steps.length end end end def worst_status(statuses) [:passed, :undefined, :pending, :skipped, :failed].find do |status| statuses.include?(status) end end def add_unused_stepdefs @runtime.unmatched_step_definitions.each do |step_definition| stepdef_key = StepDefKey.new(step_definition.regexp_source, step_definition.file_colon_line) @stepdef_to_match[stepdef_key] = [] end end end end end end class path fix require "cucumber/eclipse/steps/version" require 'cucumber/formatter/progress' require 'cucumber/step_definition_light' module Cucumber module Eclipse module Steps class Json < Cucumber::Formatter::Progress include Cucumber::Formatter::Console class StepDefKey < Cucumber::StepDefinitionLight attr_accessor :mean_duration, :status end def initialize(runtime, path_or_io, options) @runtime = runtime @io = ensure_io(path_or_io, "usage") @options = options @stepdef_to_match = Hash.new{|h,stepdef_key| h[stepdef_key] = []} end def before_features(features) print_profile_information end def before_step(step) @step = step @start_time = Time.now end def before_step_result(*args) @duration = Time.now - @start_time end def after_step_result(keyword, step_match, multiline_arg, status, exception, source_indent, background, file_colon_line) step_definition = step_match.step_definition unless step_definition.nil? # nil if it's from a scenario outline stepdef_key = StepDefKey.new(step_definition.regexp_source, step_definition.file_colon_line) @stepdef_to_match[stepdef_key] << { :keyword => keyword, :step_match => step_match, :status => status, :file_colon_line => @step.file_colon_line, :duration => @duration } end super end def print_summary(features) add_unused_stepdefs aggregate_info if @options[:dry_run] keys = @stepdef_to_match.keys.sort {|a,b| a.regexp_source <=> b.regexp_source} else keys = @stepdef_to_match.keys.sort {|a,b| a.mean_duration <=> b.mean_duration}.reverse end keys.each do |stepdef_key| print_step_definition(stepdef_key) if @stepdef_to_match[stepdef_key].any? print_steps(stepdef_key) else @io.puts(" " + format_string("NOT MATCHED BY ANY STEPS", :failed)) end end @io.puts super end def print_step_definition(stepdef_key) @io.print format_string(sprintf("%.7f", stepdef_key.mean_duration), :skipped) + " " unless @options[:dry_run] @io.print format_string(stepdef_key.regexp_source, stepdef_key.status) if @options[:source] indent = max_length - stepdef_key.regexp_source.unpack('U*').length line_comment = " # #{stepdef_key.file_colon_line}".indent(indent) @io.print(format_string(line_comment, :comment)) end @io.puts end def print_steps(stepdef_key) @stepdef_to_match[stepdef_key].each do |step| @io.print " " @io.print format_string(sprintf("%.7f", step[:duration]), :skipped) + " " unless @options[:dry_run] @io.print format_step(step[:keyword], step[:step_match], step[:status], nil) if @options[:source] indent = max_length - (step[:keyword].unpack('U*').length + step[:step_match].format_args.unpack('U*').length) line_comment = " # #{step[:file_colon_line]}".indent(indent) @io.print(format_string(line_comment, :comment)) end @io.puts end end def max_length [max_stepdef_length, max_step_length].compact.max end def max_stepdef_length @stepdef_to_match.keys.flatten.map{|key| key.regexp_source.unpack('U*').length}.max end def max_step_length @stepdef_to_match.values.to_a.flatten.map do |step| step[:keyword].unpack('U*').length + step[:step_match].format_args.unpack('U*').length end.max end def aggregate_info @stepdef_to_match.each do |key, steps| if steps.empty? key.status = :skipped key.mean_duration = 0 else key.status = worst_status(steps.map{ |step| step[:status] }) total_duration = steps.inject(0) {|sum, step| step[:duration] + sum} key.mean_duration = total_duration / steps.length end end end def worst_status(statuses) [:passed, :undefined, :pending, :skipped, :failed].find do |status| statuses.include?(status) end end def add_unused_stepdefs @runtime.unmatched_step_definitions.each do |step_definition| stepdef_key = StepDefKey.new(step_definition.regexp_source, step_definition.file_colon_line) @stepdef_to_match[stepdef_key] = [] end end end end end end
# # Copyright (C) 2020 - present Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. require 'set' module DataFixup::Auditors module Migrate DEFAULT_BATCH_SIZE = 100 module AuditorWorker def initialize(account_id, date, operation_type: :backfill) @account_id = account_id @date = date @_operation = operation_type end def operation @_operation ||= :backfill end def account @_account ||= Account.find(@account_id) end def previous_sunday date_time - date_time.wday.days end def next_sunday previous_sunday + 7.days end def date_time @_dt ||= CanvasTime.try_parse("#{@date.strftime('%Y-%m-%d')} 00:00:00 -0000") end def cassandra_query_options # auditors cassandra partitions span one week. # querying a week at a time is more efficient # than separately for each day. # this query will usually span 2 partitions # because the alignment of the partitions is # to number of second from epoch % seconds_in_week { oldest: previous_sunday, newest: next_sunday, fetch_strategy: :serial } end # rubocop:disable Lint/NoSleep def get_cassandra_records_resiliantly(collection, page_args) retries = 0 max_retries = 10 begin recs = collection.paginate(page_args) return recs rescue CassandraCQL::Thrift::TimedOutException raise if retries >= max_retries sleep 1.4 ** retries retries += 1 retry end end # rubocop:enable Lint/NoSleep def filter_for_idempotency(ar_attributes_list, auditor_ar_type) # we might have inserted some of these already, try again with only new recs uuids = ar_attributes_list.map{|h| h['uuid']} existing_uuids = auditor_ar_type.where(uuid: uuids).pluck(:uuid) ar_attributes_list.reject{|h| existing_uuids.include?(h['uuid']) } end def bulk_insert_auditor_recs(auditor_ar_type, attrs_lists) partition_groups = attrs_lists.group_by{|a| auditor_ar_type.infer_partition_table_name(a) } partition_groups.each do |partition_name, partition_attrs| auditor_ar_type.transaction do auditor_ar_type.connection.bulk_insert(partition_name, partition_attrs) end end end def migrate_in_pages(collection, auditor_ar_type, batch_size=DEFAULT_BATCH_SIZE) next_page = 1 until next_page.nil? page_args = { page: next_page, per_page: batch_size} auditor_recs = get_cassandra_records_resiliantly(collection, page_args) ar_attributes_list = auditor_recs.map do |rec| auditor_ar_type.ar_attributes_from_event_stream(rec) end begin bulk_insert_auditor_recs(auditor_ar_type, ar_attributes_list) rescue ActiveRecord::RecordNotUnique, ActiveRecord::InvalidForeignKey # this gets messy if we act specifically; let's just apply both remedies new_attrs_list = filter_for_idempotency(ar_attributes_list, auditor_ar_type) new_attrs_list = filter_dead_foreign_keys(new_attrs_list) bulk_insert_auditor_recs(auditor_ar_type, new_attrs_list) if new_attrs_list.size > 0 end next_page = auditor_recs.next_page end end # repairing is run after a scheduling pass. In most cases this means some records # made it over and then the scheduled migration job failed, usually due to # repeated cassandra timeouts. For this reason, we don't wish to load ALL # scanned records from cassandra, only those that are not yet in the database. # therefore "repair" is much more careful. It scans each batch of IDs from the cassandra # index, sees which ones aren't currently in postgres, and then only loads attributes for # that subset to insert. This makes it much faster for traversing a large dataset # when some or most of the records are filled in already. Obviously it would be somewhat # slower than the migrate pass if there were NO records migrated. def repair_in_pages(ids_collection, stream_type, auditor_ar_type, batch_size=DEFAULT_BATCH_SIZE) next_page = 1 until next_page.nil? page_args = { page: next_page, per_page: batch_size} auditor_id_recs = get_cassandra_records_resiliantly(ids_collection, page_args) collect_propsed_ids = auditor_id_recs.map{|rec| rec['id']} existing_ids = auditor_ar_type.where(uuid: collect_propsed_ids).pluck(:uuid) insertable_ids = collect_propsed_ids - existing_ids if insertable_ids.size > 0 auditor_recs = stream_type.fetch(insertable_ids, strategy: :serial) ar_attributes_list = auditor_recs.map do |rec| auditor_ar_type.ar_attributes_from_event_stream(rec) end begin bulk_insert_auditor_recs(auditor_ar_type, ar_attributes_list) rescue ActiveRecord::RecordNotUnique, ActiveRecord::InvalidForeignKey # this gets messy if we act specifically; let's just apply both remedies new_attrs_list = filter_for_idempotency(ar_attributes_list, auditor_ar_type) new_attrs_list = filter_dead_foreign_keys(new_attrs_list) bulk_insert_auditor_recs(auditor_ar_type, new_attrs_list) if new_attrs_list.size > 0 end end next_page = auditor_id_recs.next_page end end def audit_in_pages(ids_collection, auditor_ar_type, batch_size=DEFAULT_BATCH_SIZE) @audit_results ||= { 'uuid_count' => 0, 'failure_count' => 0, 'missed_ids' => [] } audit_failure_uuids = [] audit_uuid_count = 0 next_page = 1 until next_page.nil? page_args = { page: next_page, per_page: batch_size} auditor_id_recs = get_cassandra_records_resiliantly(ids_collection, page_args) uuids = auditor_id_recs.map{|rec| rec['id']} audit_uuid_count += uuids.size existing_uuids = auditor_ar_type.where(uuid: uuids).pluck(:uuid) audit_failure_uuids += (uuids - existing_uuids) next_page = auditor_id_recs.next_page end @audit_results['uuid_count'] += audit_uuid_count @audit_results['failure_count'] += audit_failure_uuids.size @audit_results['missed_ids'] += audit_failure_uuids end def cell_attributes(target_date: nil) target_date = @date if target_date.nil? { auditor_type: auditor_type, account_id: account.id, year: target_date.year, month: target_date.month, day: target_date.day } end def find_migration_cell(attributes: cell_attributes) attributes = cell_attributes if attributes.nil? ::Auditors::ActiveRecord::MigrationCell.find_by(attributes) end def migration_cell @_cell ||= find_migration_cell end def create_cell!(attributes: nil) attributes = cell_attributes if attributes.nil? ::Auditors::ActiveRecord::MigrationCell.create!(attributes.merge({ completed: false, repaired: false })) rescue ActiveRecord::RecordNotUnique, PG::UniqueViolation created_cell = find_migration_cell(attributes: attributes) raise "unresolvable auditors migration state #{attributes}" if created_cell.nil? created_cell end def reset_cell! migration_cell&.destroy @_cell = nil end def mark_cell_queued!(delayed_job_id: nil) (@_cell = create_cell!) if migration_cell.nil? migration_cell.update_attribute(:failed, false) if migration_cell.failed # queueing will take care of a week, so let's make sure we don't get # other jobs vying for the same slot current_date = previous_sunday while current_date < next_sunday do cur_cell_attrs = cell_attributes(target_date: current_date) current_cell = find_migration_cell(attributes: cur_cell_attrs) current_cell = create_cell!(attributes: cur_cell_attrs) if current_cell.nil? current_cell.update(completed: false, failed: false, job_id: delayed_job_id, queued: true) current_date += 1.day end @_cell.reload end def auditors_cassandra_db_lambda lambda do timeout_value = Setting.get("auditors_backfill_cassandra_timeout", 360).to_i opts = { override_options: { 'timeout' => timeout_value } } Canvas::Cassandra::DatabaseBuilder.from_config(:auditors, opts) end end def already_complete? migration_cell&.completed end def currently_queueable? return true if migration_cell.nil? return true if migration_cell.failed if operation == :repair return false if migration_cell.repaired else return false if migration_cell.completed end return true unless migration_cell.queued # this cell is currently in the queue (maybe) # If that update happened more than a few # days ago, it's likely dead, and should # get rescheduled. Worst case # it scans and fails to find anything to do, # and marks the cell complete. return migration_cell.updated_at < 3.days.ago end def mark_week_complete! current_date = previous_sunday while current_date < next_sunday do cur_cell_attrs = cell_attributes(target_date: current_date) current_cell = find_migration_cell(attributes: cur_cell_attrs) current_cell = create_cell!(attributes: cur_cell_attrs) if current_cell.nil? repaired = (operation == :repair) current_cell.update(completed: true, failed: false, repaired: repaired) current_date += 1.day end end def mark_week_audited!(results) current_date = previous_sunday failed_count = results['failure_count'] while current_date < next_sunday do cur_cell_attrs = cell_attributes(target_date: current_date) current_cell = find_migration_cell(attributes: cur_cell_attrs) current_cell = create_cell!(attributes: cur_cell_attrs) if current_cell.nil? current_cell.update(audited: true, missing_count: failed_count) current_date += 1.day end end def perform extend_cassandra_stream_timeout! cell = migration_cell return if cell&.completed cell = create_cell! if cell.nil? if account.root_account.created_at > @date + 2.days # this account wasn't active on this day, don't # waste time migrating return cell.update_attribute(:completed, true) end if operation == :repair perform_repair elsif operation == :backfill perform_migration else raise "Unknown Auditor Backfill Operation: #{operation}" end # the reason this works is the rescheduling plan. # if the job passes, the whole week gets marked "complete". # If it fails, the target cell for this one job will get rescheduled # later in the reconciliation pass. # at that time it will again run for this whole week. # any failed day results in a job spanning a week. # If a job for another day in the SAME week runs, # and this one is done already, it will quickly short circuit because this # day is marked complete. # If two jobs from the same week happened to run at the same time, # they would contend over Uniqueness violations, which we catch and handle. mark_week_complete! ensure cell.update_attribute(:failed, true) unless cell.reload.completed cell.update_attribute(:queued, false) clear_cassandra_stream_timeout! end def audit extend_cassandra_stream_timeout! @audit_results = { 'uuid_count' => 0, 'failure_count' => 0, 'missed_ids' => [] } perform_audit mark_week_audited!(@audit_results) return @audit_results ensure clear_cassandra_stream_timeout! end def extend_cassandra_stream_timeout! Canvas::Cassandra::DatabaseBuilder.reset_connections! @_stream_db_proc = auditor_cassandra_stream.attr_config_values[:database] auditor_cassandra_stream.database(auditors_cassandra_db_lambda) end def clear_cassandra_stream_timeout! raise RuntimeError("stream db never cached!") unless @_stream_db_proc Canvas::Cassandra::DatabaseBuilder.reset_connections! auditor_cassandra_stream.database(@_stream_db_proc) end def auditor_cassandra_stream stream_map = { authentication: Auditors::Authentication::Stream, course: Auditors::Course::Stream, grade_change: Auditors::GradeChange::Stream } stream_map[auditor_type] end def auditor_type raise "NOT IMPLEMENTED" end def perform_migration raise "NOT IMPLEMENTED" end def perform_repair raise "NOT IMPLEMENTED" end def perform_audit raise "NOT IMPLEMENTED" end def filter_dead_foreign_keys(_attrs_list) raise "NOT IMPLEMENTED" end end # account = Account.find(account_id) # date = Date.civil(2020, 4, 21) # cass_class = Auditors::Authentication # ar_class = Auditors::ActiveRecord::AuthenticationRecord # worker = AuthenticationWorker.new(account, date) # Delayed::Job.enqueue(worker) class AuthenticationWorker include AuditorWorker def auditor_type :authentication end def cassandra_collection Auditors::Authentication.for_account(account, cassandra_query_options) end def cassandra_id_collection Auditors::Authentication::Stream.ids_for_account(account, cassandra_query_options) end def perform_migration migrate_in_pages(cassandra_collection, Auditors::ActiveRecord::AuthenticationRecord) end def perform_repair repair_in_pages(cassandra_id_collection, Auditors::Authentication::Stream, Auditors::ActiveRecord::AuthenticationRecord) end def perform_audit audit_in_pages(cassandra_id_collection, Auditors::ActiveRecord::AuthenticationRecord) end def filter_dead_foreign_keys(attrs_list) user_ids = attrs_list.map{|a| a['user_id'] } pseudonym_ids = attrs_list.map{|a| a['pseudonym_id'] } existing_user_ids = User.where(id: user_ids).pluck(:id) existing_pseud_ids = Pseudonym.where(id: pseudonym_ids).pluck(:id) missing_uids = user_ids - existing_user_ids missing_pids = pseudonym_ids - existing_pseud_ids new_attrs_list = attrs_list.reject{|h| missing_uids.include?(h['user_id']) } new_attrs_list.reject{|h| missing_pids.include?(h['pseudonym_id'])} end end class CourseWorker include AuditorWorker def auditor_type :course end def cassandra_collection Auditors::Course.for_account(account, cassandra_query_options) end def cassandra_id_collection Auditors::Course::Stream.ids_for_account(account, cassandra_query_options) end def perform_migration migrate_in_pages(cassandra_collection, Auditors::ActiveRecord::CourseRecord) end def perform_repair repair_in_pages(cassandra_id_collection, Auditors::Course::Stream, Auditors::ActiveRecord::CourseRecord) end def perform_audit audit_in_pages(cassandra_id_collection, Auditors::ActiveRecord::CourseRecord) end def filter_dead_foreign_keys(attrs_list) user_ids = attrs_list.map{|a| a['user_id'] } existing_user_ids = User.where(id: user_ids).pluck(:id) missing_uids = user_ids - existing_user_ids attrs_list.reject {|h| missing_uids.include?(h['user_id']) } end end class GradeChangeWorker include AuditorWorker def auditor_type :grade_change end def cassandra_collection_for(course) Auditors::GradeChange.for_course(course, cassandra_query_options) end def cassandra_id_collection_for(course) Auditors::GradeChange::Stream.ids_for_course(course, cassandra_query_options) end def migrateable_course_ids s_scope = Submission.where("course_id=courses.id").where("updated_at > ?", @date - 7.days) account.courses.active.where( "EXISTS (?)", s_scope).where( "courses.created_at <= ?", @date + 2.days).pluck(:id) end def perform_migration all_course_ids = migrateable_course_ids.to_a all_course_ids.in_groups_of(1000) do |course_ids| Course.where(id: course_ids).each do |course| migrate_in_pages(cassandra_collection_for(course), Auditors::ActiveRecord::GradeChangeRecord) end end end def perform_repair all_course_ids = migrateable_course_ids.to_a all_course_ids.in_groups_of(1000) do |course_ids| Course.where(id: course_ids).each do |course| repair_in_pages(cassandra_id_collection_for(course), Auditors::GradeChange::Stream, Auditors::ActiveRecord::GradeChangeRecord) end end end def perform_audit all_course_ids = migrateable_course_ids.to_a all_course_ids.in_groups_of(1000) do |course_ids| Course.where(id: course_ids).each do |course| audit_in_pages(cassandra_id_collection_for(course), Auditors::ActiveRecord::GradeChangeRecord) end end end def filter_dead_foreign_keys(attrs_list) student_ids = attrs_list.map{|a| a['student_id'] } grader_ids = attrs_list.map{|a| a['grader_id'] } user_ids = (student_ids + grader_ids).uniq existing_user_ids = User.where(id: user_ids).pluck(:id) missing_uids = user_ids - existing_user_ids filtered_attrs_list = attrs_list.reject do |h| missing_uids.include?(h['student_id']) || missing_uids.include?(h['grader_id']) end submission_ids = filtered_attrs_list.map{|a| a['submission_id'] } existing_submission_ids = Submission.where(id: submission_ids).pluck(:id) missing_sids = submission_ids - existing_submission_ids filtered_attrs_list.reject {|h| missing_sids.include?(h['submission_id']) } end end # sets up ALL the backfill jobs for the current shard # given some date range # remember we START with the most recent becuase # they're typically most valuable, and walk backwards, # so start_date should be > end_date. # # This job tries to be nice to the db by scheduling a day at a time # and if the queue is over the set threshold it will schedule itself to # run again in 5 minutes and see if it can schedule in any more. # This should keep the queue from growing out of control. # # Setup is something like: # start_date = Date.today # end_date = start - 10.months # worker = DataFixup::Auditors::Migrate::BackfillEngine.new(start_date, end_date) # Delayed::Job.enqueue(worker) # # It will take care of re-scheduling itself until that backfill window is covered. class BackfillEngine DEFAULT_DEPTH_THRESHOLD = 100000 DEFAULT_SCHEDULING_INTERVAL = 150 # these jobs are all low-priority, # so high-ish parallelism is ok # (they mostly run in a few minutes or less). # we'll wind it down on clusters that are # in trouble if necessary. For clusters # taking a long time, grades parallelism # could actually be increased very substantially overnight # as they will not try to overwrite each other. DEFAULT_PARALLELISM_GRADES = 20 DEFAULT_PARALLELISM_COURSES = 10 DEFAULT_PARALLELISM_AUTHS = 5 LOG_PREFIX = "Auditors PG Backfill - ".freeze SCHEDULAR_TAG = "DataFixup::Auditors::Migrate::BackfillEngine#perform" WORKER_TAGS = [ "DataFixup::Auditors::Migrate::CourseWorker#perform".freeze, "DataFixup::Auditors::Migrate::GradeChangeWorker#perform".freeze, "DataFixup::Auditors::Migrate::AuthenticationWorker#perform".freeze ].freeze class << self def non_future_queue Delayed::Job.where("run_at <= ?", Time.zone.now) end def queue_depth non_future_queue.count end def queue_tag_counts non_future_queue.group(:tag).count end def running_tag_counts non_future_queue.where('locked_by IS NOT NULL').group(:tag).count end def backfill_jobs non_future_queue.where("tag IN ('#{WORKER_TAGS.join("','")}')") end def other_jobs non_future_queue.where("tag NOT IN ('#{WORKER_TAGS.join("','")}')") end def schedular_jobs Delayed::Job.where(tag: SCHEDULAR_TAG) end def failed_jobs Delayed::Job::Failed.where("tag IN ('#{WORKER_TAGS.join("','")}')") end def failed_schedulars Delayed::Job::Failed.where(tag: SCHEDULAR_TAG) end def running_jobs backfill_jobs.where("locked_by IS NOT NULL") end def completed_cells Auditors::ActiveRecord::MigrationCell.where(completed: true) end def failed_cells Auditors::ActiveRecord::MigrationCell.where(failed: true, completed: false) end def jobs_id shard = Shard.current (shard.respond_to?(:delayed_jobs_shard_id) ? shard.delayed_jobs_shard_id : "NONE") end def queue_setting_key "auditors_backfill_queue_threshold_jobs#{jobs_id}" end def backfill_key "auditors_backfill_interval_seconds_jobs#{jobs_id}" end def queue_threshold Setting.get(queue_setting_key, DEFAULT_DEPTH_THRESHOLD).to_i end def backfill_interval Setting.get(backfill_key, DEFAULT_SCHEDULING_INTERVAL).to_i.seconds end def cluster_name Shard.current.database_server.id end def parallelism_key(auditor_type) "auditors_migration_num_strands" end def check_parallelism { grade_changes: Setting.get(parallelism_key("grade_changes"), 1), courses: Setting.get(parallelism_key("courses"), 1), authentications: Setting.get(parallelism_key("authentications"), 1) } end def longest_running(on_shard: false) longest_scope = running_jobs if on_shard longest_scope = longest_scope.where(shard_id: Shard.current.id) end longest = longest_scope.order(:locked_at).first return {} if longest.blank? { id: longest.id, elapsed_seconds: (Time.now.utc - longest.locked_at), locked_by: longest.locked_by } end def update_parallelism!(hash) hash.each do |auditor_type, parallelism_value| Setting.set(parallelism_key(auditor_type), parallelism_value) end p_settings = check_parallelism gc_tag = 'DataFixup::Auditors::Migrate::GradeChangeWorker#perform' Delayed::Job.where(tag: gc_tag, locked_by: nil).update_all(max_concurrent: p_settings[:grade_changes]) course_tag = 'DataFixup::Auditors::Migrate::CourseWorker#perform' Delayed::Job.where(tag: course_tag, locked_by: nil).update_all(max_concurrent: p_settings[:courses]) auth_tag = 'DataFixup::Auditors::Migrate::AuthenticationWorker#perform' Delayed::Job.where(tag: auth_tag, locked_by: nil).update_all(max_concurrent: p_settings[:authentications]) end # only set parallelism if it is not currently set at all. # If it's already been set (either from previous preset or # by manual action) it will have a > 0 value and this will # just exit after checking each setting def preset_parallelism! if Setting.get(parallelism_key("grade_changes"), -1).to_i < 0 Setting.set(parallelism_key("grade_changes"), DEFAULT_PARALLELISM_GRADES) end if Setting.get(parallelism_key("courses"), -1).to_i < 0 Setting.set(parallelism_key("courses"), DEFAULT_PARALLELISM_COURSES) end if Setting.get(parallelism_key("authentications"), -1).to_i < 0 Setting.set(parallelism_key("authentications"), DEFAULT_PARALLELISM_AUTHS) end end def working_dates(current_jobs_scope) current_jobs_scope.pluck(:handler).map{|h| YAML.unsafe_load(h).instance_variable_get(:@date) }.uniq end def shard_summary { 'total_depth': queue_depth, 'backfill': backfill_jobs.where(shard_id: Shard.current.id).count, 'others': other_jobs.where(shard_id: Shard.current.id).count, 'failed': failed_jobs.where(shard_id: Shard.current.id).count, 'currently_running': running_jobs.where(shard_id: Shard.current.id).count, 'completed_cells': completed_cells.count, 'dates_being_worked': working_dates(running_jobs.where(shard_id: Shard.current.id)), 'config': { 'threshold': "#{queue_threshold} jobs", 'interval': "#{backfill_interval} seconds", 'parallelism': check_parallelism }, 'longest_runner': longest_running(on_shard: true), 'schedular_count': schedular_jobs.where(shard_id: Shard.current.id).count, 'schedular_job_ids': schedular_jobs.where(shard_id: Shard.current.id).limit(10).map(&:id) } end def summary { 'total_depth': queue_depth, 'backfill': backfill_jobs.count, 'others': other_jobs.count, 'failed': failed_jobs.count, 'currently_running': running_jobs.count, 'completed_cells': completed_cells.count, # it does not work to check these with jobs from other shards # because deserializing them fails to find accounts 'dates_being_worked': working_dates(running_jobs.where(shard_id: Shard.current.id)), 'config': { 'threshold': "#{queue_threshold} jobs", 'interval': "#{backfill_interval} seconds", 'parallelism': check_parallelism }, 'longest_runner': longest_running, 'schedular_count': schedular_jobs.count, 'schedular_job_ids': schedular_jobs.limit(10).map(&:id) } end def date_summaries(start_date, end_date) cur_date = start_date output = {} while cur_date <= end_date cells = completed_cells.where(year: cur_date.year, month: cur_date.month, day: cur_date.day) output[cur_date.to_s] = cells.count cur_date += 1.day end output end def scan_for_holes(start_date, end_date) summaries = date_summaries(start_date, end_date) max_count = summaries.values.max { 'max_value': max_count, 'holes': summaries.keep_if{|_,v| v < max_count} } end def log(message) Rails.logger.info("#{LOG_PREFIX} #{message}") end def force_run_schedulars(id) d_worker = Delayed::Worker.new sched_job = Delayed::Job.find(id) sched_job.update(locked_by: 'force_run', locked_at: Time.now.utc) d_worker.perform(sched_job) end def total_reset_frd! conn = Auditors::ActiveRecord::GradeChangeRecord.connection conn.execute("set role dba") conn.truncate(Auditors::ActiveRecord::GradeChangeRecord.table_name) conn.truncate(Auditors::ActiveRecord::CourseRecord.table_name) conn.truncate(Auditors::ActiveRecord::AuthenticationRecord.table_name) conn.truncate(Auditors::ActiveRecord::MigrationCell.table_name) end end def initialize(start_date, end_date, operation_type: :schedule) if start_date < end_date raise "You probably didn't read the comment on this job..." end @start_date = start_date @end_date = end_date @_operation = operation_type end def operation @_operation ||= :schedule end def log(message) self.class.log(message) end def queue_threshold self.class.queue_threshold end def backfill_interval self.class.backfill_interval end def queue_depth self.class.queue_depth end def slim_accounts return @_accounts if @_accounts root_account_ids = Account.root_accounts.active.pluck(:id) @_accounts = Account.active.where( "root_account_id IS NULL OR root_account_id IN (?)", root_account_ids ).select(:id, :root_account_id) end def cluster_name self.class.cluster_name end def conditionally_enqueue_worker(worker, n_strand) if worker.currently_queueable? job = Delayed::Job.enqueue(worker, n_strand: n_strand, priority: Delayed::LOW_PRIORITY) worker.mark_cell_queued!(delayed_job_id: job.id) end end def generate_worker(worker_type, account, current_date) worker_operation = (operation == :repair) ? :repair : :backfill worker_type.new(account.id, current_date, operation_type: worker_operation) end def enqueue_one_day_for_account(account, current_date) if account.root_account? # auth records are stored at the root account level, # we only need to enqueue these jobs for root accounts auth_worker = generate_worker(AuthenticationWorker, account, current_date) conditionally_enqueue_worker(auth_worker, "auditors_migration") end course_worker = generate_worker(CourseWorker, account, current_date) conditionally_enqueue_worker(course_worker, "auditors_migration") grade_change_worker = generate_worker(GradeChangeWorker, account, current_date) conditionally_enqueue_worker(grade_change_worker, "auditors_migration") end def enqueue_one_day(current_date) slim_accounts.each do |account| enqueue_one_day_for_account(account, current_date) end end def schedular_strand_tag "AuditorsBackfillEngine::Job_Shard_#{self.class.jobs_id}" end def next_schedule_date(current_date) # each job spans a week, so when we're scheduling # the initial job we can schedule one week at a time. # In a repair pass, we want to make sure we hit every # cell that failed, or that never got queued (just in case), # so we actually line up jobs for each day that is # missing/failed. It's possible to schedule multiple jobs # for the same week. If one completes before the next one starts, # they will bail immediately. If two from the same week are running # at the same time the uniqueness-constraint-and-conflict-handling # prevents them from creating duplicates if operation == :schedule current_date - 7.days elsif operation == :repair current_date - 1.day else raise "Unknown backfill operation: #{operation}" end end def perform self.class.preset_parallelism! log("Scheduling Auditors Backfill!") current_date = @start_date while current_date >= @end_date if queue_depth >= queue_threshold log("Queue too deep (#{queue_depth}) for threshold (#{queue_threshold}), throttling...") break end enqueue_one_day(current_date) log("Scheduled Backfill for #{current_date} on #{Shard.current.id}") # jobs span a week now, we can schedule them at week intervals arbitrarily current_date = next_schedule_date(current_date) end if current_date >= @end_date schedule_worker = BackfillEngine.new(current_date, @end_date) next_time = Time.now.utc + backfill_interval log("More work to do. Scheduling another job for #{next_time}") Delayed::Job.enqueue(schedule_worker, run_at: next_time, priority: Delayed::LOW_PRIORITY, n_strand: schedular_strand_tag, max_attempts: 5) else log("WE DID IT. Shard #{Shard.current.id} has auditors migrated (probably, check the migration cell records to be sure)") end end end # useful for generating cassandra records in test environments # to make migration practice more real. # Probably should never run in production. Ever. class DataFixtures # pulled from one day on FFT # as a sample size AUTH_VOLUME = 275000 COURSE_VOLUME = 8000 GRADE_CHANGE_VOLUME = 175000 def generate_authentications puts("generating auth records...") pseudonyms = Pseudonym.active.limit(2000) event_count = 0 while event_count < AUTH_VOLUME event_record = Auditors::Authentication::Record.generate(pseudonyms.sample, 'login') Auditors::Authentication::Stream.insert(event_record, {backend_strategy: :cassandra}) event_count += 1 puts("...#{event_count}") if event_count % 1000 == 0 end end def generate_courses puts("generating course event records...") courses = Course.active.limit(1000) users = User.active.limit(1000) event_count = 0 while event_count < COURSE_VOLUME event_record = Auditors::Course::Record.generate(courses.sample, users.sample, 'published', {}, {}) Auditors::Course::Stream.insert(event_record, {backend_strategy: :cassandra}) if Auditors.write_to_cassandra? event_count += 1 puts("...#{event_count}") if event_count % 1000 == 0 end end def generate_grade_changes puts("generating grade change records...") assignments = Assignment.active.limit(10000) event_count = 0 while event_count < GRADE_CHANGE_VOLUME assignment = assignments.sample assignment.submissions.each do |sub| event_record = Auditors::GradeChange::Record.generate(sub, 'graded') Auditors::GradeChange::Stream.insert(event_record, {backend_strategy: :cassandra}) if Auditors.write_to_cassandra? event_count += 1 puts("...#{event_count}") if event_count % 1000 == 0 end end end def generate generate_authentications generate_courses generate_grade_changes end end end end log auditor bulk inserts refs CNVS-48876 flag = none TEST PLAN: 1) run backfill 2) find cells missing records 3) uuid lists should be logged at bulk insert time Change-Id: Iadcb625146d8aa2b38e31051cef848cc587eca94 Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/238829 Reviewed-by: Jacob Burroughs <8ecea6e385af5cf9f53123f5ca17fb5fd6a6d4b2@instructure.com> Reviewed-by: Simon Williams <088e16a1019277b15d58faf0541e11910eb756f6@instructure.com> Tested-by: Service Cloud Jenkins <9144042a601061f88f1e1d7a1753ea3e2972119d@instructure.com> QA-Review: Simon Williams <088e16a1019277b15d58faf0541e11910eb756f6@instructure.com> Product-Review: Ethan Vizitei <73eeb0b2f65d05a906adf3b21ee1f9f5a2aa3c1c@instructure.com> # # Copyright (C) 2020 - present Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. require 'set' module DataFixup::Auditors module Migrate DEFAULT_BATCH_SIZE = 100 module AuditorWorker def initialize(account_id, date, operation_type: :backfill) @account_id = account_id @date = date @_operation = operation_type end def operation @_operation ||= :backfill end def account @_account ||= Account.find(@account_id) end def previous_sunday date_time - date_time.wday.days end def next_sunday previous_sunday + 7.days end def date_time @_dt ||= CanvasTime.try_parse("#{@date.strftime('%Y-%m-%d')} 00:00:00 -0000") end def cassandra_query_options # auditors cassandra partitions span one week. # querying a week at a time is more efficient # than separately for each day. # this query will usually span 2 partitions # because the alignment of the partitions is # to number of second from epoch % seconds_in_week { oldest: previous_sunday, newest: next_sunday, fetch_strategy: :serial } end # rubocop:disable Lint/NoSleep def get_cassandra_records_resiliantly(collection, page_args) retries = 0 max_retries = 10 begin recs = collection.paginate(page_args) return recs rescue CassandraCQL::Thrift::TimedOutException raise if retries >= max_retries sleep 1.4 ** retries retries += 1 retry end end # rubocop:enable Lint/NoSleep def filter_for_idempotency(ar_attributes_list, auditor_ar_type) # we might have inserted some of these already, try again with only new recs uuids = ar_attributes_list.map{|h| h['uuid']} existing_uuids = auditor_ar_type.where(uuid: uuids).pluck(:uuid) ar_attributes_list.reject{|h| existing_uuids.include?(h['uuid']) } end def bulk_insert_auditor_recs(auditor_ar_type, attrs_lists) partition_groups = attrs_lists.group_by{|a| auditor_ar_type.infer_partition_table_name(a) } partition_groups.each do |partition_name, partition_attrs| uuids = partition_attrs.map{|h| h['uuid']} Rails.logger.info("INSERTING INTO #{partition_name} #{uuids.size} IDs (#{uuids.join(',')})") auditor_ar_type.transaction do auditor_ar_type.connection.bulk_insert(partition_name, partition_attrs) end end end def migrate_in_pages(collection, auditor_ar_type, batch_size=DEFAULT_BATCH_SIZE) next_page = 1 until next_page.nil? page_args = { page: next_page, per_page: batch_size} auditor_recs = get_cassandra_records_resiliantly(collection, page_args) ar_attributes_list = auditor_recs.map do |rec| auditor_ar_type.ar_attributes_from_event_stream(rec) end begin bulk_insert_auditor_recs(auditor_ar_type, ar_attributes_list) rescue ActiveRecord::RecordNotUnique, ActiveRecord::InvalidForeignKey # this gets messy if we act specifically; let's just apply both remedies new_attrs_list = filter_for_idempotency(ar_attributes_list, auditor_ar_type) new_attrs_list = filter_dead_foreign_keys(new_attrs_list) bulk_insert_auditor_recs(auditor_ar_type, new_attrs_list) if new_attrs_list.size > 0 end next_page = auditor_recs.next_page end end # repairing is run after a scheduling pass. In most cases this means some records # made it over and then the scheduled migration job failed, usually due to # repeated cassandra timeouts. For this reason, we don't wish to load ALL # scanned records from cassandra, only those that are not yet in the database. # therefore "repair" is much more careful. It scans each batch of IDs from the cassandra # index, sees which ones aren't currently in postgres, and then only loads attributes for # that subset to insert. This makes it much faster for traversing a large dataset # when some or most of the records are filled in already. Obviously it would be somewhat # slower than the migrate pass if there were NO records migrated. def repair_in_pages(ids_collection, stream_type, auditor_ar_type, batch_size=DEFAULT_BATCH_SIZE) next_page = 1 until next_page.nil? page_args = { page: next_page, per_page: batch_size} auditor_id_recs = get_cassandra_records_resiliantly(ids_collection, page_args) collect_propsed_ids = auditor_id_recs.map{|rec| rec['id']} existing_ids = auditor_ar_type.where(uuid: collect_propsed_ids).pluck(:uuid) insertable_ids = collect_propsed_ids - existing_ids if insertable_ids.size > 0 auditor_recs = stream_type.fetch(insertable_ids, strategy: :serial) ar_attributes_list = auditor_recs.map do |rec| auditor_ar_type.ar_attributes_from_event_stream(rec) end begin bulk_insert_auditor_recs(auditor_ar_type, ar_attributes_list) rescue ActiveRecord::RecordNotUnique, ActiveRecord::InvalidForeignKey # this gets messy if we act specifically; let's just apply both remedies new_attrs_list = filter_for_idempotency(ar_attributes_list, auditor_ar_type) new_attrs_list = filter_dead_foreign_keys(new_attrs_list) bulk_insert_auditor_recs(auditor_ar_type, new_attrs_list) if new_attrs_list.size > 0 end end next_page = auditor_id_recs.next_page end end def audit_in_pages(ids_collection, auditor_ar_type, batch_size=DEFAULT_BATCH_SIZE) @audit_results ||= { 'uuid_count' => 0, 'failure_count' => 0, 'missed_ids' => [] } audit_failure_uuids = [] audit_uuid_count = 0 next_page = 1 until next_page.nil? page_args = { page: next_page, per_page: batch_size} auditor_id_recs = get_cassandra_records_resiliantly(ids_collection, page_args) uuids = auditor_id_recs.map{|rec| rec['id']} audit_uuid_count += uuids.size existing_uuids = auditor_ar_type.where(uuid: uuids).pluck(:uuid) audit_failure_uuids += (uuids - existing_uuids) next_page = auditor_id_recs.next_page end @audit_results['uuid_count'] += audit_uuid_count @audit_results['failure_count'] += audit_failure_uuids.size @audit_results['missed_ids'] += audit_failure_uuids end def cell_attributes(target_date: nil) target_date = @date if target_date.nil? { auditor_type: auditor_type, account_id: account.id, year: target_date.year, month: target_date.month, day: target_date.day } end def find_migration_cell(attributes: cell_attributes) attributes = cell_attributes if attributes.nil? ::Auditors::ActiveRecord::MigrationCell.find_by(attributes) end def migration_cell @_cell ||= find_migration_cell end def create_cell!(attributes: nil) attributes = cell_attributes if attributes.nil? ::Auditors::ActiveRecord::MigrationCell.create!(attributes.merge({ completed: false, repaired: false })) rescue ActiveRecord::RecordNotUnique, PG::UniqueViolation created_cell = find_migration_cell(attributes: attributes) raise "unresolvable auditors migration state #{attributes}" if created_cell.nil? created_cell end def reset_cell! migration_cell&.destroy @_cell = nil end def mark_cell_queued!(delayed_job_id: nil) (@_cell = create_cell!) if migration_cell.nil? migration_cell.update_attribute(:failed, false) if migration_cell.failed # queueing will take care of a week, so let's make sure we don't get # other jobs vying for the same slot current_date = previous_sunday while current_date < next_sunday do cur_cell_attrs = cell_attributes(target_date: current_date) current_cell = find_migration_cell(attributes: cur_cell_attrs) current_cell = create_cell!(attributes: cur_cell_attrs) if current_cell.nil? current_cell.update(completed: false, failed: false, job_id: delayed_job_id, queued: true) current_date += 1.day end @_cell.reload end def auditors_cassandra_db_lambda lambda do timeout_value = Setting.get("auditors_backfill_cassandra_timeout", 360).to_i opts = { override_options: { 'timeout' => timeout_value } } Canvas::Cassandra::DatabaseBuilder.from_config(:auditors, opts) end end def already_complete? migration_cell&.completed end def currently_queueable? return true if migration_cell.nil? return true if migration_cell.failed if operation == :repair return false if migration_cell.repaired else return false if migration_cell.completed end return true unless migration_cell.queued # this cell is currently in the queue (maybe) # If that update happened more than a few # days ago, it's likely dead, and should # get rescheduled. Worst case # it scans and fails to find anything to do, # and marks the cell complete. return migration_cell.updated_at < 3.days.ago end def mark_week_complete! current_date = previous_sunday while current_date < next_sunday do cur_cell_attrs = cell_attributes(target_date: current_date) current_cell = find_migration_cell(attributes: cur_cell_attrs) current_cell = create_cell!(attributes: cur_cell_attrs) if current_cell.nil? repaired = (operation == :repair) current_cell.update(completed: true, failed: false, repaired: repaired) current_date += 1.day end end def mark_week_audited!(results) current_date = previous_sunday failed_count = results['failure_count'] while current_date < next_sunday do cur_cell_attrs = cell_attributes(target_date: current_date) current_cell = find_migration_cell(attributes: cur_cell_attrs) current_cell = create_cell!(attributes: cur_cell_attrs) if current_cell.nil? current_cell.update(audited: true, missing_count: failed_count) current_date += 1.day end end def perform extend_cassandra_stream_timeout! cell = migration_cell return if cell&.completed cell = create_cell! if cell.nil? if account.root_account.created_at > @date + 2.days # this account wasn't active on this day, don't # waste time migrating return cell.update_attribute(:completed, true) end if operation == :repair perform_repair elsif operation == :backfill perform_migration else raise "Unknown Auditor Backfill Operation: #{operation}" end # the reason this works is the rescheduling plan. # if the job passes, the whole week gets marked "complete". # If it fails, the target cell for this one job will get rescheduled # later in the reconciliation pass. # at that time it will again run for this whole week. # any failed day results in a job spanning a week. # If a job for another day in the SAME week runs, # and this one is done already, it will quickly short circuit because this # day is marked complete. # If two jobs from the same week happened to run at the same time, # they would contend over Uniqueness violations, which we catch and handle. mark_week_complete! ensure cell.update_attribute(:failed, true) unless cell.reload.completed cell.update_attribute(:queued, false) clear_cassandra_stream_timeout! end def audit extend_cassandra_stream_timeout! @audit_results = { 'uuid_count' => 0, 'failure_count' => 0, 'missed_ids' => [] } perform_audit mark_week_audited!(@audit_results) return @audit_results ensure clear_cassandra_stream_timeout! end def extend_cassandra_stream_timeout! Canvas::Cassandra::DatabaseBuilder.reset_connections! @_stream_db_proc = auditor_cassandra_stream.attr_config_values[:database] auditor_cassandra_stream.database(auditors_cassandra_db_lambda) end def clear_cassandra_stream_timeout! raise RuntimeError("stream db never cached!") unless @_stream_db_proc Canvas::Cassandra::DatabaseBuilder.reset_connections! auditor_cassandra_stream.database(@_stream_db_proc) end def auditor_cassandra_stream stream_map = { authentication: Auditors::Authentication::Stream, course: Auditors::Course::Stream, grade_change: Auditors::GradeChange::Stream } stream_map[auditor_type] end def auditor_type raise "NOT IMPLEMENTED" end def perform_migration raise "NOT IMPLEMENTED" end def perform_repair raise "NOT IMPLEMENTED" end def perform_audit raise "NOT IMPLEMENTED" end def filter_dead_foreign_keys(_attrs_list) raise "NOT IMPLEMENTED" end end # account = Account.find(account_id) # date = Date.civil(2020, 4, 21) # cass_class = Auditors::Authentication # ar_class = Auditors::ActiveRecord::AuthenticationRecord # worker = AuthenticationWorker.new(account, date) # Delayed::Job.enqueue(worker) class AuthenticationWorker include AuditorWorker def auditor_type :authentication end def cassandra_collection Auditors::Authentication.for_account(account, cassandra_query_options) end def cassandra_id_collection Auditors::Authentication::Stream.ids_for_account(account, cassandra_query_options) end def perform_migration migrate_in_pages(cassandra_collection, Auditors::ActiveRecord::AuthenticationRecord) end def perform_repair repair_in_pages(cassandra_id_collection, Auditors::Authentication::Stream, Auditors::ActiveRecord::AuthenticationRecord) end def perform_audit audit_in_pages(cassandra_id_collection, Auditors::ActiveRecord::AuthenticationRecord) end def filter_dead_foreign_keys(attrs_list) user_ids = attrs_list.map{|a| a['user_id'] } pseudonym_ids = attrs_list.map{|a| a['pseudonym_id'] } existing_user_ids = User.where(id: user_ids).pluck(:id) existing_pseud_ids = Pseudonym.where(id: pseudonym_ids).pluck(:id) missing_uids = user_ids - existing_user_ids missing_pids = pseudonym_ids - existing_pseud_ids new_attrs_list = attrs_list.reject{|h| missing_uids.include?(h['user_id']) } new_attrs_list.reject{|h| missing_pids.include?(h['pseudonym_id'])} end end class CourseWorker include AuditorWorker def auditor_type :course end def cassandra_collection Auditors::Course.for_account(account, cassandra_query_options) end def cassandra_id_collection Auditors::Course::Stream.ids_for_account(account, cassandra_query_options) end def perform_migration migrate_in_pages(cassandra_collection, Auditors::ActiveRecord::CourseRecord) end def perform_repair repair_in_pages(cassandra_id_collection, Auditors::Course::Stream, Auditors::ActiveRecord::CourseRecord) end def perform_audit audit_in_pages(cassandra_id_collection, Auditors::ActiveRecord::CourseRecord) end def filter_dead_foreign_keys(attrs_list) user_ids = attrs_list.map{|a| a['user_id'] } existing_user_ids = User.where(id: user_ids).pluck(:id) missing_uids = user_ids - existing_user_ids attrs_list.reject {|h| missing_uids.include?(h['user_id']) } end end class GradeChangeWorker include AuditorWorker def auditor_type :grade_change end def cassandra_collection_for(course) Auditors::GradeChange.for_course(course, cassandra_query_options) end def cassandra_id_collection_for(course) Auditors::GradeChange::Stream.ids_for_course(course, cassandra_query_options) end def migrateable_course_ids s_scope = Submission.where("course_id=courses.id").where("updated_at > ?", @date - 7.days) account.courses.active.where( "EXISTS (?)", s_scope).where( "courses.created_at <= ?", @date + 2.days).pluck(:id) end def perform_migration all_course_ids = migrateable_course_ids.to_a all_course_ids.in_groups_of(1000) do |course_ids| Course.where(id: course_ids).each do |course| migrate_in_pages(cassandra_collection_for(course), Auditors::ActiveRecord::GradeChangeRecord) end end end def perform_repair all_course_ids = migrateable_course_ids.to_a all_course_ids.in_groups_of(1000) do |course_ids| Course.where(id: course_ids).each do |course| repair_in_pages(cassandra_id_collection_for(course), Auditors::GradeChange::Stream, Auditors::ActiveRecord::GradeChangeRecord) end end end def perform_audit all_course_ids = migrateable_course_ids.to_a all_course_ids.in_groups_of(1000) do |course_ids| Course.where(id: course_ids).each do |course| audit_in_pages(cassandra_id_collection_for(course), Auditors::ActiveRecord::GradeChangeRecord) end end end def filter_dead_foreign_keys(attrs_list) student_ids = attrs_list.map{|a| a['student_id'] } grader_ids = attrs_list.map{|a| a['grader_id'] } user_ids = (student_ids + grader_ids).uniq existing_user_ids = User.where(id: user_ids).pluck(:id) missing_uids = user_ids - existing_user_ids filtered_attrs_list = attrs_list.reject do |h| missing_uids.include?(h['student_id']) || missing_uids.include?(h['grader_id']) end submission_ids = filtered_attrs_list.map{|a| a['submission_id'] } existing_submission_ids = Submission.where(id: submission_ids).pluck(:id) missing_sids = submission_ids - existing_submission_ids filtered_attrs_list.reject {|h| missing_sids.include?(h['submission_id']) } end end # sets up ALL the backfill jobs for the current shard # given some date range # remember we START with the most recent becuase # they're typically most valuable, and walk backwards, # so start_date should be > end_date. # # This job tries to be nice to the db by scheduling a day at a time # and if the queue is over the set threshold it will schedule itself to # run again in 5 minutes and see if it can schedule in any more. # This should keep the queue from growing out of control. # # Setup is something like: # start_date = Date.today # end_date = start - 10.months # worker = DataFixup::Auditors::Migrate::BackfillEngine.new(start_date, end_date) # Delayed::Job.enqueue(worker) # # It will take care of re-scheduling itself until that backfill window is covered. class BackfillEngine DEFAULT_DEPTH_THRESHOLD = 100000 DEFAULT_SCHEDULING_INTERVAL = 150 # these jobs are all low-priority, # so high-ish parallelism is ok # (they mostly run in a few minutes or less). # we'll wind it down on clusters that are # in trouble if necessary. For clusters # taking a long time, grades parallelism # could actually be increased very substantially overnight # as they will not try to overwrite each other. DEFAULT_PARALLELISM_GRADES = 20 DEFAULT_PARALLELISM_COURSES = 10 DEFAULT_PARALLELISM_AUTHS = 5 LOG_PREFIX = "Auditors PG Backfill - ".freeze SCHEDULAR_TAG = "DataFixup::Auditors::Migrate::BackfillEngine#perform" WORKER_TAGS = [ "DataFixup::Auditors::Migrate::CourseWorker#perform".freeze, "DataFixup::Auditors::Migrate::GradeChangeWorker#perform".freeze, "DataFixup::Auditors::Migrate::AuthenticationWorker#perform".freeze ].freeze class << self def non_future_queue Delayed::Job.where("run_at <= ?", Time.zone.now) end def queue_depth non_future_queue.count end def queue_tag_counts non_future_queue.group(:tag).count end def running_tag_counts non_future_queue.where('locked_by IS NOT NULL').group(:tag).count end def backfill_jobs non_future_queue.where("tag IN ('#{WORKER_TAGS.join("','")}')") end def other_jobs non_future_queue.where("tag NOT IN ('#{WORKER_TAGS.join("','")}')") end def schedular_jobs Delayed::Job.where(tag: SCHEDULAR_TAG) end def failed_jobs Delayed::Job::Failed.where("tag IN ('#{WORKER_TAGS.join("','")}')") end def failed_schedulars Delayed::Job::Failed.where(tag: SCHEDULAR_TAG) end def running_jobs backfill_jobs.where("locked_by IS NOT NULL") end def completed_cells Auditors::ActiveRecord::MigrationCell.where(completed: true) end def failed_cells Auditors::ActiveRecord::MigrationCell.where(failed: true, completed: false) end def jobs_id shard = Shard.current (shard.respond_to?(:delayed_jobs_shard_id) ? shard.delayed_jobs_shard_id : "NONE") end def queue_setting_key "auditors_backfill_queue_threshold_jobs#{jobs_id}" end def backfill_key "auditors_backfill_interval_seconds_jobs#{jobs_id}" end def queue_threshold Setting.get(queue_setting_key, DEFAULT_DEPTH_THRESHOLD).to_i end def backfill_interval Setting.get(backfill_key, DEFAULT_SCHEDULING_INTERVAL).to_i.seconds end def cluster_name Shard.current.database_server.id end def parallelism_key(auditor_type) "auditors_migration_num_strands" end def check_parallelism { grade_changes: Setting.get(parallelism_key("grade_changes"), 1), courses: Setting.get(parallelism_key("courses"), 1), authentications: Setting.get(parallelism_key("authentications"), 1) } end def longest_running(on_shard: false) longest_scope = running_jobs if on_shard longest_scope = longest_scope.where(shard_id: Shard.current.id) end longest = longest_scope.order(:locked_at).first return {} if longest.blank? { id: longest.id, elapsed_seconds: (Time.now.utc - longest.locked_at), locked_by: longest.locked_by } end def update_parallelism!(hash) hash.each do |auditor_type, parallelism_value| Setting.set(parallelism_key(auditor_type), parallelism_value) end p_settings = check_parallelism gc_tag = 'DataFixup::Auditors::Migrate::GradeChangeWorker#perform' Delayed::Job.where(tag: gc_tag, locked_by: nil).update_all(max_concurrent: p_settings[:grade_changes]) course_tag = 'DataFixup::Auditors::Migrate::CourseWorker#perform' Delayed::Job.where(tag: course_tag, locked_by: nil).update_all(max_concurrent: p_settings[:courses]) auth_tag = 'DataFixup::Auditors::Migrate::AuthenticationWorker#perform' Delayed::Job.where(tag: auth_tag, locked_by: nil).update_all(max_concurrent: p_settings[:authentications]) end # only set parallelism if it is not currently set at all. # If it's already been set (either from previous preset or # by manual action) it will have a > 0 value and this will # just exit after checking each setting def preset_parallelism! if Setting.get(parallelism_key("grade_changes"), -1).to_i < 0 Setting.set(parallelism_key("grade_changes"), DEFAULT_PARALLELISM_GRADES) end if Setting.get(parallelism_key("courses"), -1).to_i < 0 Setting.set(parallelism_key("courses"), DEFAULT_PARALLELISM_COURSES) end if Setting.get(parallelism_key("authentications"), -1).to_i < 0 Setting.set(parallelism_key("authentications"), DEFAULT_PARALLELISM_AUTHS) end end def working_dates(current_jobs_scope) current_jobs_scope.pluck(:handler).map{|h| YAML.unsafe_load(h).instance_variable_get(:@date) }.uniq end def shard_summary { 'total_depth': queue_depth, 'backfill': backfill_jobs.where(shard_id: Shard.current.id).count, 'others': other_jobs.where(shard_id: Shard.current.id).count, 'failed': failed_jobs.where(shard_id: Shard.current.id).count, 'currently_running': running_jobs.where(shard_id: Shard.current.id).count, 'completed_cells': completed_cells.count, 'dates_being_worked': working_dates(running_jobs.where(shard_id: Shard.current.id)), 'config': { 'threshold': "#{queue_threshold} jobs", 'interval': "#{backfill_interval} seconds", 'parallelism': check_parallelism }, 'longest_runner': longest_running(on_shard: true), 'schedular_count': schedular_jobs.where(shard_id: Shard.current.id).count, 'schedular_job_ids': schedular_jobs.where(shard_id: Shard.current.id).limit(10).map(&:id) } end def summary { 'total_depth': queue_depth, 'backfill': backfill_jobs.count, 'others': other_jobs.count, 'failed': failed_jobs.count, 'currently_running': running_jobs.count, 'completed_cells': completed_cells.count, # it does not work to check these with jobs from other shards # because deserializing them fails to find accounts 'dates_being_worked': working_dates(running_jobs.where(shard_id: Shard.current.id)), 'config': { 'threshold': "#{queue_threshold} jobs", 'interval': "#{backfill_interval} seconds", 'parallelism': check_parallelism }, 'longest_runner': longest_running, 'schedular_count': schedular_jobs.count, 'schedular_job_ids': schedular_jobs.limit(10).map(&:id) } end def date_summaries(start_date, end_date) cur_date = start_date output = {} while cur_date <= end_date cells = completed_cells.where(year: cur_date.year, month: cur_date.month, day: cur_date.day) output[cur_date.to_s] = cells.count cur_date += 1.day end output end def scan_for_holes(start_date, end_date) summaries = date_summaries(start_date, end_date) max_count = summaries.values.max { 'max_value': max_count, 'holes': summaries.keep_if{|_,v| v < max_count} } end def log(message) Rails.logger.info("#{LOG_PREFIX} #{message}") end def force_run_schedulars(id) d_worker = Delayed::Worker.new sched_job = Delayed::Job.find(id) sched_job.update(locked_by: 'force_run', locked_at: Time.now.utc) d_worker.perform(sched_job) end def total_reset_frd! conn = Auditors::ActiveRecord::GradeChangeRecord.connection conn.execute("set role dba") conn.truncate(Auditors::ActiveRecord::GradeChangeRecord.table_name) conn.truncate(Auditors::ActiveRecord::CourseRecord.table_name) conn.truncate(Auditors::ActiveRecord::AuthenticationRecord.table_name) conn.truncate(Auditors::ActiveRecord::MigrationCell.table_name) end end def initialize(start_date, end_date, operation_type: :schedule) if start_date < end_date raise "You probably didn't read the comment on this job..." end @start_date = start_date @end_date = end_date @_operation = operation_type end def operation @_operation ||= :schedule end def log(message) self.class.log(message) end def queue_threshold self.class.queue_threshold end def backfill_interval self.class.backfill_interval end def queue_depth self.class.queue_depth end def slim_accounts return @_accounts if @_accounts root_account_ids = Account.root_accounts.active.pluck(:id) @_accounts = Account.active.where( "root_account_id IS NULL OR root_account_id IN (?)", root_account_ids ).select(:id, :root_account_id) end def cluster_name self.class.cluster_name end def conditionally_enqueue_worker(worker, n_strand) if worker.currently_queueable? job = Delayed::Job.enqueue(worker, n_strand: n_strand, priority: Delayed::LOW_PRIORITY) worker.mark_cell_queued!(delayed_job_id: job.id) end end def generate_worker(worker_type, account, current_date) worker_operation = (operation == :repair) ? :repair : :backfill worker_type.new(account.id, current_date, operation_type: worker_operation) end def enqueue_one_day_for_account(account, current_date) if account.root_account? # auth records are stored at the root account level, # we only need to enqueue these jobs for root accounts auth_worker = generate_worker(AuthenticationWorker, account, current_date) conditionally_enqueue_worker(auth_worker, "auditors_migration") end course_worker = generate_worker(CourseWorker, account, current_date) conditionally_enqueue_worker(course_worker, "auditors_migration") grade_change_worker = generate_worker(GradeChangeWorker, account, current_date) conditionally_enqueue_worker(grade_change_worker, "auditors_migration") end def enqueue_one_day(current_date) slim_accounts.each do |account| enqueue_one_day_for_account(account, current_date) end end def schedular_strand_tag "AuditorsBackfillEngine::Job_Shard_#{self.class.jobs_id}" end def next_schedule_date(current_date) # each job spans a week, so when we're scheduling # the initial job we can schedule one week at a time. # In a repair pass, we want to make sure we hit every # cell that failed, or that never got queued (just in case), # so we actually line up jobs for each day that is # missing/failed. It's possible to schedule multiple jobs # for the same week. If one completes before the next one starts, # they will bail immediately. If two from the same week are running # at the same time the uniqueness-constraint-and-conflict-handling # prevents them from creating duplicates if operation == :schedule current_date - 7.days elsif operation == :repair current_date - 1.day else raise "Unknown backfill operation: #{operation}" end end def perform self.class.preset_parallelism! log("Scheduling Auditors Backfill!") current_date = @start_date while current_date >= @end_date if queue_depth >= queue_threshold log("Queue too deep (#{queue_depth}) for threshold (#{queue_threshold}), throttling...") break end enqueue_one_day(current_date) log("Scheduled Backfill for #{current_date} on #{Shard.current.id}") # jobs span a week now, we can schedule them at week intervals arbitrarily current_date = next_schedule_date(current_date) end if current_date >= @end_date schedule_worker = BackfillEngine.new(current_date, @end_date) next_time = Time.now.utc + backfill_interval log("More work to do. Scheduling another job for #{next_time}") Delayed::Job.enqueue(schedule_worker, run_at: next_time, priority: Delayed::LOW_PRIORITY, n_strand: schedular_strand_tag, max_attempts: 5) else log("WE DID IT. Shard #{Shard.current.id} has auditors migrated (probably, check the migration cell records to be sure)") end end end # useful for generating cassandra records in test environments # to make migration practice more real. # Probably should never run in production. Ever. class DataFixtures # pulled from one day on FFT # as a sample size AUTH_VOLUME = 275000 COURSE_VOLUME = 8000 GRADE_CHANGE_VOLUME = 175000 def generate_authentications puts("generating auth records...") pseudonyms = Pseudonym.active.limit(2000) event_count = 0 while event_count < AUTH_VOLUME event_record = Auditors::Authentication::Record.generate(pseudonyms.sample, 'login') Auditors::Authentication::Stream.insert(event_record, {backend_strategy: :cassandra}) event_count += 1 puts("...#{event_count}") if event_count % 1000 == 0 end end def generate_courses puts("generating course event records...") courses = Course.active.limit(1000) users = User.active.limit(1000) event_count = 0 while event_count < COURSE_VOLUME event_record = Auditors::Course::Record.generate(courses.sample, users.sample, 'published', {}, {}) Auditors::Course::Stream.insert(event_record, {backend_strategy: :cassandra}) if Auditors.write_to_cassandra? event_count += 1 puts("...#{event_count}") if event_count % 1000 == 0 end end def generate_grade_changes puts("generating grade change records...") assignments = Assignment.active.limit(10000) event_count = 0 while event_count < GRADE_CHANGE_VOLUME assignment = assignments.sample assignment.submissions.each do |sub| event_record = Auditors::GradeChange::Record.generate(sub, 'graded') Auditors::GradeChange::Stream.insert(event_record, {backend_strategy: :cassandra}) if Auditors.write_to_cassandra? event_count += 1 puts("...#{event_count}") if event_count % 1000 == 0 end end end def generate generate_authentications generate_courses generate_grade_changes end end end end
require 'zk' module DCell module Registry class ZkAdapter include Node include Global PREFIX = "/dcell" DEFAULT_PORT = 2181 # Create a new connection to Zookeeper # # servers: a list of Zookeeper servers to connect to. Each server in the # list has a host/port configuration def initialize(options) # Stringify keys :/ options = options.inject({}) { |h,(k,v)| h[k.to_s] = v; h } @env = options['env'] || 'production' @base_path = "#{PREFIX}/#{@env}" # Let them specify a single server instead of many server = options['server'] if server servers = [server] else servers = options['servers'] raise "no Zookeeper servers given" unless servers end # Add the default Zookeeper port unless specified servers.map! do |server| if server[/:\d+$/] server else "#{server}:#{DEFAULT_PORT}" end end @zk = ZK.new(*servers) @node_registry = Registry.new(@zk, @base_path, :nodes, true) @global_registry = Registry.new(@zk, @base_path, :globals, false) end class Registry def initialize(zk, base_path, name, ephemeral) @zk = zk @base_path = File.join(base_path, name.to_s) @ephemeral = ephemeral @zk.mkdir_p @base_path end def get(key) result, _ = @zk.get("#{@base_path}/#{key}", watch: true) MessagePack.unpack(result, options={:symbolize_keys => true}) if result rescue ZK::Exceptions::NoNode end def _set(key, value, unique) path = "#{@base_path}/#{key}" @zk.create path, value.to_msgpack, :ephemeral => @ephemeral rescue ZK::Exceptions::NodeExists raise KeyExists if unique @zk.set path, value.to_msgpack end def set(key, value) _set(key, value, false) end def all @zk.children @base_path end def remove(key) path = "#{@base_path}/#{key}" @zk.delete path end def clear_all all.each do |key| remove key end @zk.rm_rf @base_path @zk.mkdir_p @base_path end end end end end registries:zk: properly handle removal of non-existant key require 'zk' module DCell module Registry class ZkAdapter include Node include Global PREFIX = "/dcell" DEFAULT_PORT = 2181 # Create a new connection to Zookeeper # # servers: a list of Zookeeper servers to connect to. Each server in the # list has a host/port configuration def initialize(options) # Stringify keys :/ options = options.inject({}) { |h,(k,v)| h[k.to_s] = v; h } @env = options['env'] || 'production' @base_path = "#{PREFIX}/#{@env}" # Let them specify a single server instead of many server = options['server'] if server servers = [server] else servers = options['servers'] raise "no Zookeeper servers given" unless servers end # Add the default Zookeeper port unless specified servers.map! do |server| if server[/:\d+$/] server else "#{server}:#{DEFAULT_PORT}" end end @zk = ZK.new(*servers) @node_registry = Registry.new(@zk, @base_path, :nodes, true) @global_registry = Registry.new(@zk, @base_path, :globals, false) end class Registry def initialize(zk, base_path, name, ephemeral) @zk = zk @base_path = File.join(base_path, name.to_s) @ephemeral = ephemeral @zk.mkdir_p @base_path end def get(key) result, _ = @zk.get("#{@base_path}/#{key}", watch: true) MessagePack.unpack(result, options={:symbolize_keys => true}) if result rescue ZK::Exceptions::NoNode end def _set(key, value, unique) path = "#{@base_path}/#{key}" @zk.create path, value.to_msgpack, :ephemeral => @ephemeral rescue ZK::Exceptions::NodeExists raise KeyExists if unique @zk.set path, value.to_msgpack end def set(key, value) _set(key, value, false) end def all @zk.children @base_path end def remove(key) path = "#{@base_path}/#{key}" begin @zk.delete path rescue ZK::Exceptions::NoNode end end def clear_all all.each do |key| remove key end @zk.rm_rf @base_path @zk.mkdir_p @base_path end end end end end
module Dialog module API module Interlocutor # Lists all interlocutors # @return [Array] def interlocutors get("b/#{bot_id}/interlocutors") end # Retrieves an interlocutor # @param id [String] Interlocutor Id # @return [Hash] def interlocutor(id) get("b/#{bot_id}/interlocutors#{id}") end # Creates an interlocutor # @param attributes [Hash] # @return [Hash] def create_interlocutor(attributes) post("b/#{bot_id}/interlocutors", body: { interlocutor: attributes }) end end end end Standardize argument names module Dialog module API module Interlocutor # Lists all interlocutors # @return [Array] def interlocutors get("b/#{bot_id}/interlocutors") end # Retrieves an interlocutor # @param id [String] Interlocutor Id # @return [Hash] def interlocutor(id) get("b/#{bot_id}/interlocutors#{id}") end # Creates an interlocutor # @param payload [Hash] # @return [Hash] def create_interlocutor(payload) post("b/#{bot_id}/interlocutors", body: { interlocutor: payload }) end end end end
module DismalTony # :nodoc: # Represents the result of running VIBase#query! for a query. # Functions as a rich join of the return message and the changed conversation state, with formatting options. class HandledResponse # The VI's reply to a query. Whatever you want said back to the user. attr_reader :outgoing_message # A ConversationState object representing the User's new state after running the query attr_reader :conversation_state # Formatting options for how to display the return message attr_reader :format # Creates a new response with +rm+ serving as the outgoing message, and +cs+ the conversation state def initialize(rm = '', cs = DismalTony::ConversationState.new) @outgoing_message = rm @conversation_state = cs @format = {} end # Clones using the Marlshal dump / load trick. def clone Marshal::load(Marshal.dump(self)) end # Returns #outgoing_message def to_s @outgoing_message end # Returns the error response, which is the same as #finish with a message of <tt>"~e:frown I'm sorry, I didn't understand that!"</tt> def self.error finish("~e:frown I'm sorry, I didn't understand that!") end # Produces a new HandledResponse with a blank ConversationState and a return message of +rm+ def self.finish(rm = '') new_state = DismalTony::ConversationState.new(idle: true, use_next: nil, next_directive: nil, next_method: nil, data: nil, parse_next: true) new(rm, new_state) end # Creates a response whose ConversationState redirects control flow. Passes on next_directive, next_method, data, and parse_next via the +opts+ hash. def self.then_do(**opts) new_state = DismalTony::ConversationState.new(idle: false, next_directive: opts[:directive].name, next_method: (opts[:method] || :run), data: opts[:data], parse_next: opts.fetch(:parse_next) { true } ) new(opts[:message], new_state) end # Allows you to append formatting options +form+ to a Class Method created response easily. def with_format(**form) @format = form self end end end Changed a #[] to a #fetch module DismalTony # :nodoc: # Represents the result of running VIBase#query! for a query. # Functions as a rich join of the return message and the changed conversation state, with formatting options. class HandledResponse # The VI's reply to a query. Whatever you want said back to the user. attr_reader :outgoing_message # A ConversationState object representing the User's new state after running the query attr_reader :conversation_state # Formatting options for how to display the return message attr_reader :format # Creates a new response with +rm+ serving as the outgoing message, and +cs+ the conversation state def initialize(rm = '', cs = DismalTony::ConversationState.new) @outgoing_message = rm @conversation_state = cs @format = {} end # Clones using the Marlshal dump / load trick. def clone Marshal::load(Marshal.dump(self)) end # Returns #outgoing_message def to_s @outgoing_message end # Returns the error response, which is the same as #finish with a message of <tt>"~e:frown I'm sorry, I didn't understand that!"</tt> def self.error finish("~e:frown I'm sorry, I didn't understand that!") end # Produces a new HandledResponse with a blank ConversationState and a return message of +rm+ def self.finish(rm = '') new_state = DismalTony::ConversationState.new(idle: true, use_next: nil, next_directive: nil, next_method: nil, data: nil, parse_next: true) new(rm, new_state) end # Creates a response whose ConversationState redirects control flow. Passes on next_directive, next_method, data, and parse_next via the +opts+ hash. def self.then_do(**opts) new_state = DismalTony::ConversationState.new(idle: false, next_directive: opts[:directive].name, next_method: (opts[:method] || :run), data: opts[:data], parse_next: opts.fetch(:parse_next) { true } ) new(opts.fetch(:message) { '' }, new_state) end # Allows you to append formatting options +form+ to a Class Method created response easily. def with_format(**form) @format = form self end end end
require 'json' require 'puppet' require 'puppet/network/http_pool' require 'uri' require 'dm-core' module DataMapper module Adapters class PuppetdbAdapter < AbstractAdapter attr_accessor :http, :host, :port, :ssl def read(query) model = query.model query.filter_records(puppetdb_get(model.storage_name(model.repository_name), build_query(query))) end private def initialize(name, options = {}) super Puppet.initialize_settings unless Puppet[:confdir] # Set some defaults @host = @options[:host] || 'puppetdb' @port = @options[:port] || 443 @ssl = @options[:ssl] || true @http = Puppet::Network::HttpPool.http_instance(@host, @port, @ssl) end ## # contruct a puppetdb query from a datamapper query def build_query(query) conditions = query.conditions if conditions.nil? nil else puppetdb_condition(conditions, query.model) end end ## # return puppetdb syntax for a condition def puppetdb_condition(c, model) case c when DataMapper::Query::Conditions::NullOperation nil when DataMapper::Query::Conditions::AbstractOperation q = [c.class.slug.to_s, *c.operands.map { |o| puppetdb_condition o, model }.compact] # In case we couldn't build any query from the contained # conditions return nil instead of a empty and return q.last if q.count == 2 return nil if q.count < 2 return q end # Determine the property we should match on if c.subject.kind_of? DataMapper::Property property = c.subject elsif c.subject.kind_of? DataMapper::Associations::Relationship property = c.subject.parent_key.first else puts "Unhandled subject #{c.subject.inspect}" raise RuntimeError, "Unhandled subject #{c.subject.inspect}" end # We can only do comparison on certain fields # on the server side if property.model.respond_to? :server_fields return nil unless property.model.server_fields.include? property.name end case c when DataMapper::Query::Conditions::EqualToComparison ['=', property.field, format_value(c.value)] when DataMapper::Query::Conditions::RegexpComparison ['~', property.field, format_value(c.value)] when DataMapper::Query::Conditions::LessThanComparison ['<', property.field, format_value(c.value)] when DataMapper::Query::Conditions::GreaterThanComparison ['>', property.field, format_value(c.value)] # The following comparison operators aren't supported by PuppetDB # So we emulate them when DataMapper::Query::Conditions::LikeComparison ['~', property.field, c.value.gsub('%', '.*')] when DataMapper::Query::Conditions::LessThanOrEqualToComparison ['or', ['=', property.field, format_value(c.value)], ['<', property.field, format_value(c.value)]] when DataMapper::Query::Conditions::GreaterThanOrEqualToComparison ['or', ['=', property.field, format_value(c.value)], ['>', property.field, format_value(c.value)]] when DataMapper::Query::Conditions::InclusionComparison if c.value.kind_of? Range ['or', ['=', property.field, format_value(c.value.first)], ['>', property.field, format_value(c.value.first)], ['<', property.field, format_value(c.value.last)], ['=', property.field, format_value(c.value.last)]] else ['or', *c.value.collect { |v| ['=', property.field, format_value(v.value)]} ] end end end ## # format a value in a query # especially make sure timestamps have correct format def format_value(value) if value.is_a? Date or value.is_a? Time value.strftime('%FT%T.%LZ') else value end end def puppetdb_get(path, query=nil) uri = "/#{path}?query=" uri += URI.escape query.to_json.to_s unless query.nil? resp = @http.get(uri, { "Accept" => "application/json" }) raise RuntimeError, "PuppetDB query error: [#{resp.code}] #{resp.msg}, endpoint: #{path}, query: #{query.to_json}" unless resp.kind_of?(Net::HTTPSuccess) # Do a ugly hack because Hash and Array # properties aren't supported so we preserve them as JSON JSON.parse(resp.body).collect do |i| i.each do |k,v| i[k] = v.to_json if v.is_a? Hash or v.is_a? Array end end end end end end Handle searching using Resources as values Handle DataMapper::Resource values by getting their key value and using that as value. require 'json' require 'puppet' require 'puppet/network/http_pool' require 'uri' require 'dm-core' module DataMapper module Adapters class PuppetdbAdapter < AbstractAdapter attr_accessor :http, :host, :port, :ssl def read(query) model = query.model query.filter_records(puppetdb_get(model.storage_name(model.repository_name), build_query(query))) end private def initialize(name, options = {}) super Puppet.initialize_settings unless Puppet[:confdir] # Set some defaults @host = @options[:host] || 'puppetdb' @port = @options[:port] || 443 @ssl = @options[:ssl] || true @http = Puppet::Network::HttpPool.http_instance(@host, @port, @ssl) end ## # contruct a puppetdb query from a datamapper query def build_query(query) conditions = query.conditions if conditions.nil? nil else puppetdb_condition(conditions, query.model) end end ## # return puppetdb syntax for a condition def puppetdb_condition(c, model) case c when DataMapper::Query::Conditions::NullOperation nil when DataMapper::Query::Conditions::AbstractOperation q = [c.class.slug.to_s, *c.operands.map { |o| puppetdb_condition o, model }.compact] # In case we couldn't build any query from the contained # conditions return nil instead of a empty and return q.last if q.count == 2 return nil if q.count < 2 return q end # Determine the property we should match on if c.subject.kind_of? DataMapper::Property property = c.subject elsif c.subject.kind_of? DataMapper::Associations::Relationship property = c.subject.parent_key.first else puts "Unhandled subject #{c.subject.inspect}" raise RuntimeError, "Unhandled subject #{c.subject.inspect}" end # We can only do comparison on certain fields # on the server side if property.model.respond_to? :server_fields return nil unless property.model.server_fields.include? property.name end case c when DataMapper::Query::Conditions::EqualToComparison ['=', property.field, format_value(c.value)] when DataMapper::Query::Conditions::RegexpComparison ['~', property.field, format_value(c.value)] when DataMapper::Query::Conditions::LessThanComparison ['<', property.field, format_value(c.value)] when DataMapper::Query::Conditions::GreaterThanComparison ['>', property.field, format_value(c.value)] # The following comparison operators aren't supported by PuppetDB # So we emulate them when DataMapper::Query::Conditions::LikeComparison ['~', property.field, c.value.gsub('%', '.*')] when DataMapper::Query::Conditions::LessThanOrEqualToComparison ['or', ['=', property.field, format_value(c.value)], ['<', property.field, format_value(c.value)]] when DataMapper::Query::Conditions::GreaterThanOrEqualToComparison ['or', ['=', property.field, format_value(c.value)], ['>', property.field, format_value(c.value)]] when DataMapper::Query::Conditions::InclusionComparison if c.value.kind_of? Range ['or', ['=', property.field, format_value(c.value.first)], ['>', property.field, format_value(c.value.first)], ['<', property.field, format_value(c.value.last)], ['=', property.field, format_value(c.value.last)]] else ['or', *c.value.collect { |v| ['=', property.field, format_value(v.value)]} ] end end end ## # format a value in a query # especially make sure timestamps have correct format def format_value(value) if value.is_a? Date or value.is_a? Time value.strftime('%FT%T.%LZ') elsif value.is_a? DataMapper::Resource value.key.first else value end end def puppetdb_get(path, query=nil) uri = "/#{path}?query=" uri += URI.escape query.to_json.to_s unless query.nil? resp = @http.get(uri, { "Accept" => "application/json" }) raise RuntimeError, "PuppetDB query error: [#{resp.code}] #{resp.msg}, endpoint: #{path}, query: #{query.to_json}" unless resp.kind_of?(Net::HTTPSuccess) # Do a ugly hack because Hash and Array # properties aren't supported so we preserve them as JSON JSON.parse(resp.body).collect do |i| i.each do |k,v| i[k] = v.to_json if v.is_a? Hash or v.is_a? Array end end end end end end
# encoding: utf-8 require 'fileutils' require_relative '../../IRCPlugin' require_relative '../../LayoutableText' class Kanastats < IRCPlugin Description = "Statistics plugin logging all public conversation and \ providing tools to analyze it." Dependencies = [ :StorageYAML ] Commands = { :hirastats => 'Returns hiragana usage statistics.', :katastats => 'Returns katakana usage statistics.', :charstats => 'How often the specified char was publicly used.', :wordstats => 'How often the specified word or character was used in logged public conversation.', :logged => 'Displays information about the log files.', :wordfight! => 'Compares count of words in logged public conversation.', :cjkstats => 'Counts number of all CJK characters ever written in public conversation. Also outputs the top 10 CJK characters, or top n to n+10 if a number is provided, e.g. .cjkstats 20.', } def afterLoad @storage = @plugin_manager.plugins[:StorageYAML] @stats = @storage.read('kanastats') || {} dir = @config[:data_directory] dir ||= @storage.config[:data_directory] dir ||= '~/.ircbot' @data_directory = File.expand_path(dir).chomp('/') @log_file = "#{@data_directory}/public_logfile" end def beforeUnload @log_file = nil @data_directory = nil @stats = nil @storage = nil nil end def store @storage.write('kanastats', @stats) end def on_privmsg(msg) case msg.bot_command when :hirastats output_group_stats(msg, 'Hiragana stats: ', ALL_HIRAGANA) when :katastats output_group_stats(msg, 'Katakana stats: ', ALL_KATAKANA) when :charstats charstat(msg) when :wordstats wordstats(msg) when :logged logged(msg) when :wordfight! wordfight(msg) when :cjkstats cjkstats(msg) else unless msg.private? statify(msg.message) log(msg.message) end end end def statify(text) return unless text text.each_char do |c| @stats[c] ||= 0 @stats[c] += 1 end store end ALL_HIRAGANA = 'あいうえおかきくけこさしすせそたちつてとなにぬねのまみむめもはひふへほやゆよらりるれろわゐゑをんばびぶべぼぱぴぷぺぽがぎぐげござじずぜぞだぢづでどゃゅょぁぃぅぇぉっ' ALL_KATAKANA = 'アイウエオカキクケコサシスセソタチツテトナニヌネノマミムメモハヒフヘホヤユヨラリルレロワヰヱヲンバビブベボパピプペポガギグゲゴザジズゼゾダヂヅデドャュョァィゥェォッ' def output_group_stats(msg, prefix, symbols_array) output_array = symbols_array.each_char.sort_by do |c| -@stats[c] || 0 end.map do |c| "#{c} #{@stats[c] || 0}" end.to_a msg.reply( LayoutableText::Prefixed.new( prefix, LayoutableText::SimpleJoined.new(' ', output_array) ) ) end def contains_cjk?(s) !!(s =~ /\p{Han}|\p{Katakana}|\p{Hiragana}|\p{Hangul}/) end def cjkstats(msg) number = 0 number = msg.tail.split.first.to_i if msg.tail counts = @stats.group_by do |c, _| if contains_cjk?(c) if ALL_HIRAGANA.include?(c) || ALL_KATAKANA.include?(c) :kana else :cjk end else :non_cjk end end top10 = counts[:cjk].sort_by {|_, v| -v} number = [0, [number, top10.size - 10].min].max top10 = top10[number, 10] cjk_count = counts[:cjk].map(&:last).inject(0, &:+) cjk_count += counts[:kana].map(&:last).inject(0, &:+) non_count = counts[:non_cjk].map(&:last).inject(0, &:+) msg.reply("#{cjk_count} CJK characters and #{non_count} non-CJK characters were written.") msg.reply( LayoutableText::Prefixed.new( "Top #{number+1} to #{number+10} non-kana CJK characters: ", LayoutableText::SimpleJoined.new(' ', top10) ) ) end def charstat(msg) word = msg.tail return unless word c = word[0] count = @stats[c] || 0 msg.reply("The char '#{c}' #{used_text(count)}.") end def log(line) return unless line File.open(@log_file, 'a') { |f| f.write(line + "\n") } end def wordstats(msg) word = msg.tail return unless word count = count_logfile( word ) msg.reply("The word '#{word}' #{used_text(count)}.") end def used_text(count) case count when 0 "wasn't used so far" when 1 'was used once' else "was used #{count} times" end end RANDOM_FUNNY_REPLIES = [ 'Kanastats online and fully operational.', 'Kanastats is watching you.', ] def logged(msg) count = File.foreach(@log_file).count msg.reply( "#{RANDOM_FUNNY_REPLIES.sample} Currently #{count} lines and #{@stats.size} different characters have been logged." ) end def count_logfile(word) File.open(@log_file) do |f| f.each_line.inject(0) do |sum, l| sum + l.scan(word).size end end end def wordfight(msg) return unless msg.tail words = msg.tail.split(/[[:space:]]+/) return unless words.length >= 1 words = words.uniq word_counts = words.zip(words.map { |w| count_logfile(w) }) msg.reply(WordFightLayouter.new(word_counts)) end class WordFightLayouter < LayoutableText::Arrayed def initialize(arr, *args) # Sort by occurrence count. super(arr.sort_by {|_, s| -s}, *args) end protected def format_chunk(arr, chunk_size, is_last_line) chunk = arr.slice(0, chunk_size) # Chunk into equivalence classes by occurrence count. chunk = chunk.chunk {|_, s| s}.map(&:last) chunk.map do |equiv| equiv.map do |w, s| "#{w} (#{s})" end.join(' = ') end.join(' > ') end end end Avoid potential NPE on incomplete kana in Kanastats # encoding: utf-8 require 'fileutils' require_relative '../../IRCPlugin' require_relative '../../LayoutableText' class Kanastats < IRCPlugin Description = "Statistics plugin logging all public conversation and \ providing tools to analyze it." Dependencies = [ :StorageYAML ] Commands = { :hirastats => 'Returns hiragana usage statistics.', :katastats => 'Returns katakana usage statistics.', :charstats => 'How often the specified char was publicly used.', :wordstats => 'How often the specified word or character was used in logged public conversation.', :logged => 'Displays information about the log files.', :wordfight! => 'Compares count of words in logged public conversation.', :cjkstats => 'Counts number of all CJK characters ever written in public conversation. Also outputs the top 10 CJK characters, or top n to n+10 if a number is provided, e.g. .cjkstats 20.', } def afterLoad @storage = @plugin_manager.plugins[:StorageYAML] @stats = @storage.read('kanastats') || {} dir = @config[:data_directory] dir ||= @storage.config[:data_directory] dir ||= '~/.ircbot' @data_directory = File.expand_path(dir).chomp('/') @log_file = "#{@data_directory}/public_logfile" end def beforeUnload @log_file = nil @data_directory = nil @stats = nil @storage = nil nil end def store @storage.write('kanastats', @stats) end def on_privmsg(msg) case msg.bot_command when :hirastats output_group_stats(msg, 'Hiragana stats: ', ALL_HIRAGANA) when :katastats output_group_stats(msg, 'Katakana stats: ', ALL_KATAKANA) when :charstats charstat(msg) when :wordstats wordstats(msg) when :logged logged(msg) when :wordfight! wordfight(msg) when :cjkstats cjkstats(msg) else unless msg.private? statify(msg.message) log(msg.message) end end end def statify(text) return unless text text.each_char do |c| @stats[c] ||= 0 @stats[c] += 1 end store end ALL_HIRAGANA = 'あいうえおかきくけこさしすせそたちつてとなにぬねのまみむめもはひふへほやゆよらりるれろわゐゑをんばびぶべぼぱぴぷぺぽがぎぐげござじずぜぞだぢづでどゃゅょぁぃぅぇぉっ' ALL_KATAKANA = 'アイウエオカキクケコサシスセソタチツテトナニヌネノマミムメモハヒフヘホヤユヨラリルレロワヰヱヲンバビブベボパピプペポガギグゲゴザジズゼゾダヂヅデドャュョァィゥェォッ' def output_group_stats(msg, prefix, symbols_array) output_array = symbols_array.each_char.sort_by do |c| -(@stats[c] || 0) end.map do |c| "#{c} #{@stats[c] || 0}" end.to_a msg.reply( LayoutableText::Prefixed.new( prefix, LayoutableText::SimpleJoined.new(' ', output_array) ) ) end def contains_cjk?(s) !!(s =~ /\p{Han}|\p{Katakana}|\p{Hiragana}|\p{Hangul}/) end def cjkstats(msg) number = 0 number = msg.tail.split.first.to_i if msg.tail counts = @stats.group_by do |c, _| if contains_cjk?(c) if ALL_HIRAGANA.include?(c) || ALL_KATAKANA.include?(c) :kana else :cjk end else :non_cjk end end top10 = counts[:cjk].sort_by {|_, v| -v} number = [0, [number, top10.size - 10].min].max top10 = top10[number, 10] cjk_count = counts[:cjk].map(&:last).inject(0, &:+) cjk_count += counts[:kana].map(&:last).inject(0, &:+) non_count = counts[:non_cjk].map(&:last).inject(0, &:+) msg.reply("#{cjk_count} CJK characters and #{non_count} non-CJK characters were written.") msg.reply( LayoutableText::Prefixed.new( "Top #{number+1} to #{number+10} non-kana CJK characters: ", LayoutableText::SimpleJoined.new(' ', top10) ) ) end def charstat(msg) word = msg.tail return unless word c = word[0] count = @stats[c] || 0 msg.reply("The char '#{c}' #{used_text(count)}.") end def log(line) return unless line File.open(@log_file, 'a') { |f| f.write(line + "\n") } end def wordstats(msg) word = msg.tail return unless word count = count_logfile( word ) msg.reply("The word '#{word}' #{used_text(count)}.") end def used_text(count) case count when 0 "wasn't used so far" when 1 'was used once' else "was used #{count} times" end end RANDOM_FUNNY_REPLIES = [ 'Kanastats online and fully operational.', 'Kanastats is watching you.', ] def logged(msg) count = File.foreach(@log_file).count msg.reply( "#{RANDOM_FUNNY_REPLIES.sample} Currently #{count} lines and #{@stats.size} different characters have been logged." ) end def count_logfile(word) File.open(@log_file) do |f| f.each_line.inject(0) do |sum, l| sum + l.scan(word).size end end end def wordfight(msg) return unless msg.tail words = msg.tail.split(/[[:space:]]+/) return unless words.length >= 1 words = words.uniq word_counts = words.zip(words.map { |w| count_logfile(w) }) msg.reply(WordFightLayouter.new(word_counts)) end class WordFightLayouter < LayoutableText::Arrayed def initialize(arr, *args) # Sort by occurrence count. super(arr.sort_by {|_, s| -s}, *args) end protected def format_chunk(arr, chunk_size, is_last_line) chunk = arr.slice(0, chunk_size) # Chunk into equivalence classes by occurrence count. chunk = chunk.chunk {|_, s| s}.map(&:last) chunk.map do |equiv| equiv.map do |w, s| "#{w} (#{s})" end.join(' = ') end.join(' > ') end end end
Podspec
Shindo.tests('Fog::Compute::RackspaceV2 | server_tests', ['rackspace']) do service = Fog::Compute.new(:provider => 'Rackspace', :version => 'V2') link_format = { 'href' => String, 'rel' => String } server_format = { 'id' => String, 'name' => String, 'hostId' => Fog::Nullable::String, 'created' => Fog::Nullable::String, 'updated' => Fog::Nullable::String, 'status' => Fog::Nullable::String, 'progress' => Fog::Nullable::Integer, 'user_id' => Fog::Nullable::String, 'tenant_id' => Fog::Nullable::String, 'links' => [link_format], 'metadata' => Fog::Nullable::Hash } list_servers_format = { 'servers' => [server_format] } get_server_format = { 'server' => server_format.merge({ 'accessIPv4' => String, 'accessIPv6' => String, 'OS-DCF:diskConfig' => String, 'rax-bandwidth:bandwidth' => Fog::Nullable::Array, 'addresses' => Fog::Nullable::Hash, 'flavor' => { 'id' => String, 'links' => [link_format] }, 'image' => { 'id' => String, 'links' => [link_format] } }) } create_server_format = { 'server' => { 'id' => String, 'adminPass' => String, 'links' => [link_format], 'OS-DCF:diskConfig' => String } } rescue_server_format = { 'adminPass' => Fog::Nullable::String } tests('success') do server_id = nil server_name = "fog#{Time.now.to_i.to_s}" image_id = rackspace_test_image_id(service) flavor_id = rackspace_test_flavor_id(service) tests("#create_server(#{server_name}, #{image_id}, #{flavor_id}, 1, 1)").formats(create_server_format) do body = service.create_server(server_name, image_id, flavor_id, 1, 1).body server_id = body['server']['id'] body end wait_for_server_state(service, server_id, 'ACTIVE', 'ERROR') tests("#create_server(#{server_name}, '', #{flavor_id}, 1, 1, :boot_volume_id => bootable_volume_id)").succeeds do # First, create a bootable volume. volume_service = Fog::Rackspace::BlockStorage.new bootable_volume_id = volume_service.create_volume(100, :image_id => image_id) wait_for_volume_state(volume_service, bootable_volume_id, 'available') body = service.create_server(server_name, '', flavor_id, 1, 1, :boot_volume_id => bootable_volume_id).body bfv_server_id = body['server']['id'] wait_for_server_state(service, bfv_server_id, 'ACTIVE', 'ERROR') service.delete_server(bfv_server_id) volume_service.delete_volume(bootable_volume_id) end tests("#create_server(#{server_name}, '', #{flavor_id}, 1, 1, :boot_image_id => #{image_id})").succeeds do body = service.create_server(server_name, '', flavor_id, 1, 1, :boot_image_id => image_id) bfv_server_id = body['server']['id'] wait_for_server_state(service, bfv_server_id, 'ACTIVE', 'ERROR') service.delete_server(bfv_server_id) end tests('#list_servers').formats(list_servers_format, false) do service.list_servers.body end tests('#get_server').formats(get_server_format, false) do service.get_server(server_id).body end tests("#update_server(#{server_id}, #{server_name}_update) LEGACY").formats(get_server_format) do service.update_server(server_id, "#{server_name}_update").body end tests("#update_server(#{server_id}, { 'name' => #{server_name}_update)} ").formats(get_server_format) do service.update_server(server_id, 'name' => "#{server_name}_update").body end tests('#change_server_password').succeeds do service.change_server_password(server_id, 'some_server_password') end wait_for_server_state(service, server_id, 'ACTIVE', 'ERROR') tests('#reboot_server').succeeds do service.reboot_server(server_id, 'SOFT') end wait_for_server_state(service, server_id, 'ACTIVE') tests('#rebuild_server').succeeds do rebuild_image_id = image_id service.rebuild_server(server_id, rebuild_image_id) end wait_for_server_state(service, server_id, 'ACTIVE', 'ERROR') sleep 120 unless Fog.mocking? tests('#resize_server').succeeds do resize_flavor_id = Fog.mocking? ? flavor_id : service.flavors[1].id service.resize_server(server_id, resize_flavor_id) end wait_for_server_state(service, server_id, 'VERIFY_RESIZE', 'ACTIVE') tests('#confirm_resize_server').succeeds do service.confirm_resize_server(server_id) end wait_for_server_state(service, server_id, 'ACTIVE', 'ERROR') tests('#resize_server').succeeds do resize_flavor_id = Fog.mocking? ? flavor_id : service.flavors[2].id service.resize_server(server_id, resize_flavor_id) end wait_for_server_state(service, server_id, 'VERIFY_RESIZE', 'ACTIVE') tests('#revert_resize_server').succeeds do service.revert_resize_server(server_id) end wait_for_server_state(service, server_id, 'ACTIVE', 'ERROR') tests('#rescue_server').formats(rescue_server_format, false) do service.rescue_server(server_id) end wait_for_server_state(service, server_id, 'RESCUE', 'ACTIVE') tests('#unrescue_server').succeeds do service.unrescue_server(server_id) end wait_for_server_state(service, server_id, 'ACTIVE', 'ERROR') tests('#delete_server').succeeds do service.delete_server(server_id) end end end Give the BFV servers different names. Shindo.tests('Fog::Compute::RackspaceV2 | server_tests', ['rackspace']) do service = Fog::Compute.new(:provider => 'Rackspace', :version => 'V2') link_format = { 'href' => String, 'rel' => String } server_format = { 'id' => String, 'name' => String, 'hostId' => Fog::Nullable::String, 'created' => Fog::Nullable::String, 'updated' => Fog::Nullable::String, 'status' => Fog::Nullable::String, 'progress' => Fog::Nullable::Integer, 'user_id' => Fog::Nullable::String, 'tenant_id' => Fog::Nullable::String, 'links' => [link_format], 'metadata' => Fog::Nullable::Hash } list_servers_format = { 'servers' => [server_format] } get_server_format = { 'server' => server_format.merge({ 'accessIPv4' => String, 'accessIPv6' => String, 'OS-DCF:diskConfig' => String, 'rax-bandwidth:bandwidth' => Fog::Nullable::Array, 'addresses' => Fog::Nullable::Hash, 'flavor' => { 'id' => String, 'links' => [link_format] }, 'image' => { 'id' => String, 'links' => [link_format] } }) } create_server_format = { 'server' => { 'id' => String, 'adminPass' => String, 'links' => [link_format], 'OS-DCF:diskConfig' => String } } rescue_server_format = { 'adminPass' => Fog::Nullable::String } tests('success') do server_id = nil server_name = "fog#{Time.now.to_i.to_s}" image_id = rackspace_test_image_id(service) flavor_id = rackspace_test_flavor_id(service) tests("#create_server(#{server_name}, #{image_id}, #{flavor_id}, 1, 1)").formats(create_server_format) do body = service.create_server(server_name, image_id, flavor_id, 1, 1).body server_id = body['server']['id'] body end wait_for_server_state(service, server_id, 'ACTIVE', 'ERROR') tests("#create_server(#{server_name}_bfv_1, '', #{flavor_id}, 1, 1, :boot_volume_id => bootable_volume_id)").succeeds do # First, create a bootable volume. volume_service = Fog::Rackspace::BlockStorage.new bootable_volume_id = volume_service.create_volume(100, :image_id => image_id).body['volume']['id'] wait_for_volume_state(volume_service, bootable_volume_id, 'available') body = service.create_server(server_name + "_bfv_1", '', flavor_id, 1, 1, :boot_volume_id => bootable_volume_id).body bfv_server_id = body['server']['id'] wait_for_server_state(service, bfv_server_id, 'ACTIVE', 'ERROR') service.delete_server(bfv_server_id) volume_service.delete_volume(bootable_volume_id) end tests("#create_server(#{server_name}_bfv_2, '', #{flavor_id}, 1, 1, :boot_image_id => #{image_id})").succeeds do body = service.create_server(server_name + "_bfv_2", '', flavor_id, 1, 1, :boot_image_id => image_id) bfv_server_id = body['server']['id'] wait_for_server_state(service, bfv_server_id, 'ACTIVE', 'ERROR') service.delete_server(bfv_server_id) end tests('#list_servers').formats(list_servers_format, false) do service.list_servers.body end tests('#get_server').formats(get_server_format, false) do service.get_server(server_id).body end tests("#update_server(#{server_id}, #{server_name}_update) LEGACY").formats(get_server_format) do service.update_server(server_id, "#{server_name}_update").body end tests("#update_server(#{server_id}, { 'name' => #{server_name}_update)} ").formats(get_server_format) do service.update_server(server_id, 'name' => "#{server_name}_update").body end tests('#change_server_password').succeeds do service.change_server_password(server_id, 'some_server_password') end wait_for_server_state(service, server_id, 'ACTIVE', 'ERROR') tests('#reboot_server').succeeds do service.reboot_server(server_id, 'SOFT') end wait_for_server_state(service, server_id, 'ACTIVE') tests('#rebuild_server').succeeds do rebuild_image_id = image_id service.rebuild_server(server_id, rebuild_image_id) end wait_for_server_state(service, server_id, 'ACTIVE', 'ERROR') sleep 120 unless Fog.mocking? tests('#resize_server').succeeds do resize_flavor_id = Fog.mocking? ? flavor_id : service.flavors[1].id service.resize_server(server_id, resize_flavor_id) end wait_for_server_state(service, server_id, 'VERIFY_RESIZE', 'ACTIVE') tests('#confirm_resize_server').succeeds do service.confirm_resize_server(server_id) end wait_for_server_state(service, server_id, 'ACTIVE', 'ERROR') tests('#resize_server').succeeds do resize_flavor_id = Fog.mocking? ? flavor_id : service.flavors[2].id service.resize_server(server_id, resize_flavor_id) end wait_for_server_state(service, server_id, 'VERIFY_RESIZE', 'ACTIVE') tests('#revert_resize_server').succeeds do service.revert_resize_server(server_id) end wait_for_server_state(service, server_id, 'ACTIVE', 'ERROR') tests('#rescue_server').formats(rescue_server_format, false) do service.rescue_server(server_id) end wait_for_server_state(service, server_id, 'RESCUE', 'ACTIVE') tests('#unrescue_server').succeeds do service.unrescue_server(server_id) end wait_for_server_state(service, server_id, 'ACTIVE', 'ERROR') tests('#delete_server').succeeds do service.delete_server(server_id) end end end
# encoding: UTF-8 Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'spree_stock_manager' s.version = '1.1.0' s.summary = 'TODO: Add gem summary here' s.description = 'TODO: Add (optional) gem description here' s.required_ruby_version = '>= 1.8.7' # s.author = 'You' # s.email = 'you@example.com' # s.homepage = 'http://www.spreecommerce.com' #s.files = `git ls-files`.split("\n") #s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.require_path = 'lib' s.requirements << 'none' s.add_dependency 'spree_core', '~> 1.1.0' s.add_development_dependency 'capybara', '1.0.1' s.add_development_dependency 'factory_girl', '~> 2.6.4' s.add_development_dependency 'ffaker' s.add_development_dependency 'rspec-rails', '~> 2.9' s.add_development_dependency 'sqlite3' end Update gemspec infos # encoding: UTF-8 Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'spree_stock_manager' s.version = '1.1.0' s.summary = 'TODO: Add gem summary here' s.description = 'TODO: Add (optional) gem description here' s.required_ruby_version = '>= 1.8.7' s.author = 'Olivier Buffon' # s.email = 'you@example.com' # s.homepage = 'http://www.spreecommerce.com' #s.files = `git ls-files`.split("\n") #s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.require_path = 'lib' s.requirements << 'none' s.add_dependency 'spree_core', '~> 1.1.0' s.add_development_dependency 'capybara', '1.0.1' s.add_development_dependency 'factory_girl', '~> 2.6.4' s.add_development_dependency 'ffaker' s.add_development_dependency 'rspec-rails', '~> 2.9' s.add_development_dependency 'sqlite3' end
# encoding: UTF-8 Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'spree_taxonomy_sort' s.version = '1.1.3' s.summary = 'TODO: Add gem summary here' s.description = 'TODO: Add (optional) gem description here' s.required_ruby_version = '>= 1.8.7' # s.author = 'You' # s.email = 'you@example.com' # s.homepage = 'http://www.spreecommerce.com' #s.files = `git ls-files`.split("\n") #s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.require_path = 'lib' s.requirements << 'none' s.add_dependency 'spree_core', '~> 1.1.3' s.add_development_dependency 'capybara', '1.0.1' s.add_development_dependency 'factory_girl', '~> 2.6.4' s.add_development_dependency 'ffaker' s.add_development_dependency 'rspec-rails', '~> 2.9' s.add_development_dependency 'sqlite3' end Modified spree dependency # encoding: UTF-8 Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'spree_taxonomy_sort' s.version = '1.2' s.summary = 'TODO: Add gem summary here' s.description = 'TODO: Add (optional) gem description here' s.required_ruby_version = '>= 1.8.7' # s.author = 'You' # s.email = 'you@example.com' # s.homepage = 'http://www.spreecommerce.com' #s.files = `git ls-files`.split("\n") #s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.require_path = 'lib' s.requirements << 'none' s.add_dependency 'spree_core', '> 1.1.3' s.add_development_dependency 'capybara', '1.0.1' s.add_development_dependency 'factory_girl', '~> 2.6.4' s.add_development_dependency 'ffaker' s.add_development_dependency 'rspec-rails', '~> 2.9' s.add_development_dependency 'sqlite3' end
class Hash include Enumerable # Entry stores key, value pairs in Hash. The key's hash # is also cached in the entry and recalculated when the # Hash#rehash method is called. class Entry attr_accessor :key attr_accessor :key_hash attr_accessor :value attr_accessor :next packed! [:@key, :@key_hash, :@value, :@next] def initialize(key, key_hash, value) @key = key @key_hash = key_hash @value = value end def match?(key, key_hash) case key when Symbol, Fixnum return key.equal?(@key) end @key_hash == key_hash and key.eql? @key end end # An external iterator that returns only entry chains from the # Hash storage, never nil bins. While somewhat following the API # of Enumerator, it is named Iterator because it does not provide # <code>#each</code> and should not conflict with +Enumerator+ in # MRI 1.8.7+. Returned by <code>Hash#to_iter</code>. class Iterator attr_reader :index def initialize(entries, capacity) @entries = entries @capacity = capacity @index = -1 end # Returns the next object or +nil+. def next(entry) if entry and entry = entry.next return entry end while (@index += 1) < @capacity if entry = @entries[@index] return entry end end end end # Hash methods attr_reader :size alias_method :length, :size Entries = Rubinius::Tuple # Initial size of Hash. MUST be a power of 2. MIN_SIZE = 16 # Allocate more storage when this full. This value grows with # the size of the Hash so that the max load factor is 0.75. MAX_ENTRIES = 12 # Overridden in lib/1.8.7 or lib/1.9 def self.[](*args) if args.size == 1 obj = args.first if obj.kind_of? Hash return new.replace(obj) elsif obj.respond_to? :to_hash return new.replace(Type.coerce_to(obj, Hash, :to_hash)) elsif obj.is_a?(Array) # See redmine # 1385 h = {} args.first.each do |arr| next unless arr.respond_to? :to_ary arr = arr.to_ary next unless (1..2).include? arr.size h[arr.at(0)] = arr.at(1) end return h end end return new if args.empty? if args.size & 1 == 1 raise ArgumentError, "Expected an even number, got #{args.length}" end hash = new i = args.to_iter 2 while i.next hash[i.item] = i.at(1) end hash end def self.new_from_literal(size) new end # Creates a fully-formed instance of Hash. def self.allocate hash = super() Rubinius.privately { hash.setup } hash end def ==(other) return true if self.equal? other unless other.kind_of? Hash return false unless other.respond_to? :to_hash return other == self end return false unless other.size == size Thread.detect_recursion self, other do i = to_iter while entry = i.next(entry) return false unless other[entry.key] == entry.value end end true end alias_method :eql?, :== def hash val = size Thread.detect_outermost_recursion self do i = to_iter while entry = i.next(entry) val ^= entry.key.hash val ^= entry.value.hash end end return val end def [](key) if entry = find_entry(key) entry.value else default key end end def []=(key, value) redistribute @entries if @size > @max_entries key_hash = key.hash index = key_hash & @mask # key_index key_hash entry = @entries[index] unless entry @entries[index] = new_entry key, key_hash, value return value end if entry.match? key, key_hash return entry.value = value end last = entry entry = entry.next while entry if entry.match? key, key_hash return entry.value = value end last = entry entry = entry.next end last.next = new_entry key, key_hash, value value end alias_method :store, :[]= # Used internally to get around subclasses redefining #[]= alias_method :__store__, :[]= def clear setup self end def default(key = undefined) # current MRI documentation comment is wrong. Actual behavior is: # Hash.new { 1 }.default # => nil if @default_proc key.equal?(undefined) ? nil : @default.call(self, key) else @default end end def default=(value) @default_proc = false @default = value end def default_proc @default if @default_proc end def delete(key) key_hash = key.hash index = key_index key_hash if entry = @entries[index] if entry.match? key, key_hash @entries[index] = entry.next @size -= 1 return entry.value end last = entry while entry = entry.next if entry.match? key, key_hash last.next = entry.next @size -= 1 return entry.value end last = entry end end return yield(key) if block_given? end def delete_if(&block) return to_enum :delete_if unless block_given? select(&block).each { |k, v| delete k } self end def dup hash = self.class.new hash.send :initialize_copy, self hash.taint if self.tainted? hash end def each return to_enum :each unless block_given? i = to_iter while entry = i.next(entry) yield [entry.key, entry.value] end self end def each_key return to_enum :each_key unless block_given? i = to_iter while entry = i.next(entry) yield entry.key end self end def each_pair return to_enum :each_pair unless block_given? i = to_iter while entry = i.next(entry) yield entry.key, entry.value end self end def each_value return to_enum :each_value unless block_given? i = to_iter while entry = i.next(entry) yield entry.value end self end # Returns true if there are no entries. def empty? @size == 0 end def fetch(key, default = undefined) if entry = find_entry(key) return entry.value end return yield(key) if block_given? return default unless default.equal?(undefined) raise IndexError, 'key not found' end # Searches for an entry matching +key+. Returns the entry # if found. Otherwise returns +nil+. def find_entry(key) key_hash = key.hash entry = @entries[key_index(key_hash)] while entry if entry.match? key, key_hash return entry end entry = entry.next end end private :find_entry def index(value) i = to_iter while entry = i.next(entry) return entry.key if entry.value == value end nil end def initialize(default = undefined, &block) if !default.equal?(undefined) and block raise ArgumentError, "Specify a default or a block, not both" end if block @default = block @default_proc = true elsif !default.equal?(undefined) @default = default @default_proc = false end end private :initialize def initialize_copy(other) replace other end private :initialize_copy def inspect out = [] return '{...}' if Thread.detect_recursion self do i = to_iter while entry = i.next(entry) str = entry.key.inspect str << '=>' str << entry.value.inspect out << str end end "{#{out.join ', '}}" end def invert inverted = {} i = to_iter while entry = i.next(entry) inverted[entry.value] = entry.key end inverted end def key?(key) find_entry(key) != nil end alias_method :has_key?, :key? alias_method :include?, :key? alias_method :member?, :key? # Calculates the +@entries+ slot given a key_hash value. def key_index(key_hash) key_hash & @mask end private :key_index def keys map { |key, value| key } end def merge(other, &block) dup.merge!(other, &block) end def merge!(other) other = Type.coerce_to other, Hash, :to_hash i = other.to_iter while entry = i.next(entry) key = entry.key if block_given? and key? key self.__store__ key, yield(key, self[key], entry.value) else self.__store__ key, entry.value end end self end alias_method :update, :merge! # Returns a new +Entry+ instance having +key+, +key_hash+, # and +value+. If +key+ is a kind of +String+, +key+ is # duped and frozen. def new_entry(key, key_hash, value) if key.kind_of? String key = key.dup key.freeze end @size += 1 Entry.new key, key_hash, value end private :new_entry # Adjusts the hash storage and redistributes the entries among # the new bins. Any Iterator instance will be invalid after a # call to #redistribute. Does not recalculate the cached key_hash # values. See +#rehash+. def redistribute(entries) capacity = @capacity # TODO: grow smaller too setup @capacity * 2, @max_entries * 2, @size i = -1 while (i += 1) < capacity next unless old = entries[i] while old old.next = nil if nxt = old.next index = key_index old.key_hash if entry = @entries[index] old.next = entry end @entries[index] = old old = nxt end end end # Recalculates the cached key_hash values and reorders the entries # into a new +@entries+ vector. Does NOT change the size of the # hash. See +#redistribute+. def rehash capacity = @capacity entries = @entries @entries = Entries.new @capacity i = -1 while (i += 1) < capacity next unless old = entries[i] while old old.next = nil if nxt = old.next index = key_index(old.key_hash = old.key.hash) if entry = @entries[index] old.next = entry end @entries[index] = old old = nxt end end self end def reject(&block) return to_enum :reject unless block_given? hsh = dup hsh.reject! &block hsh end def reject! return to_enum :reject! unless block_given? rejected = select { |k, v| yield k, v } return if rejected.empty? rejected.each { |k, v| delete k } self end def replace(other) other = Type.coerce_to other, Hash, :to_hash return self if self.equal? other setup i = other.to_iter while entry = i.next(entry) __store__ entry.key, entry.value end if other.default_proc @default = other.default_proc @default_proc = true else @default = other.default @default_proc = false end self end def select return to_enum :select unless block_given? selected = [] i = to_iter while entry = i.next(entry) if yield(entry.key, entry.value) selected << [entry.key, entry.value] end end selected end def shift return default(nil) if empty? i = to_iter if entry = i.next(entry) @entries[i.index] = entry.next @size -= 1 return entry.key, entry.value end end # packed! [:@capacity, :@mask, :@max_entries, :@size, :@entries] # Sets the underlying data structures. # # @capacity is the maximum number of +@entries+. # @max_entries is the maximum number of entries before redistributing. # @size is the number of pairs, equivalent to <code>hsh.size</code>. # @entrien is the vector of storage for the entry chains. def setup(capacity=MIN_SIZE, max=MAX_ENTRIES, size=0) @capacity = capacity @mask = capacity - 1 @max_entries = max @size = size @entries = Entries.new capacity end private :setup def sort(&block) to_a.sort(&block) end def to_a select { true } end # Returns an external iterator for the bins. See +Iterator+ def to_iter Iterator.new @entries, @capacity end def to_hash self end def to_s to_a.join end def value?(value) i = to_iter while entry = i.next(entry) return true if entry.value == value end false end alias_method :has_value?, :value? def values map { |key, value| value } end def values_at(*args) args.collect { |key| self[key] } end alias_method :indexes, :values_at alias_method :indices, :values_at end Remove Hash#dup, since we don't need it class Hash include Enumerable # Entry stores key, value pairs in Hash. The key's hash # is also cached in the entry and recalculated when the # Hash#rehash method is called. class Entry attr_accessor :key attr_accessor :key_hash attr_accessor :value attr_accessor :next packed! [:@key, :@key_hash, :@value, :@next] def initialize(key, key_hash, value) @key = key @key_hash = key_hash @value = value end def match?(key, key_hash) case key when Symbol, Fixnum return key.equal?(@key) end @key_hash == key_hash and key.eql? @key end end # An external iterator that returns only entry chains from the # Hash storage, never nil bins. While somewhat following the API # of Enumerator, it is named Iterator because it does not provide # <code>#each</code> and should not conflict with +Enumerator+ in # MRI 1.8.7+. Returned by <code>Hash#to_iter</code>. class Iterator attr_reader :index def initialize(entries, capacity) @entries = entries @capacity = capacity @index = -1 end # Returns the next object or +nil+. def next(entry) if entry and entry = entry.next return entry end while (@index += 1) < @capacity if entry = @entries[@index] return entry end end end end # Hash methods attr_reader :size alias_method :length, :size Entries = Rubinius::Tuple # Initial size of Hash. MUST be a power of 2. MIN_SIZE = 16 # Allocate more storage when this full. This value grows with # the size of the Hash so that the max load factor is 0.75. MAX_ENTRIES = 12 # Overridden in lib/1.8.7 or lib/1.9 def self.[](*args) if args.size == 1 obj = args.first if obj.kind_of? Hash return new.replace(obj) elsif obj.respond_to? :to_hash return new.replace(Type.coerce_to(obj, Hash, :to_hash)) elsif obj.is_a?(Array) # See redmine # 1385 h = {} args.first.each do |arr| next unless arr.respond_to? :to_ary arr = arr.to_ary next unless (1..2).include? arr.size h[arr.at(0)] = arr.at(1) end return h end end return new if args.empty? if args.size & 1 == 1 raise ArgumentError, "Expected an even number, got #{args.length}" end hash = new i = args.to_iter 2 while i.next hash[i.item] = i.at(1) end hash end def self.new_from_literal(size) new end # Creates a fully-formed instance of Hash. def self.allocate hash = super() Rubinius.privately { hash.setup } hash end def ==(other) return true if self.equal? other unless other.kind_of? Hash return false unless other.respond_to? :to_hash return other == self end return false unless other.size == size Thread.detect_recursion self, other do i = to_iter while entry = i.next(entry) return false unless other[entry.key] == entry.value end end true end alias_method :eql?, :== def hash val = size Thread.detect_outermost_recursion self do i = to_iter while entry = i.next(entry) val ^= entry.key.hash val ^= entry.value.hash end end return val end def [](key) if entry = find_entry(key) entry.value else default key end end def []=(key, value) redistribute @entries if @size > @max_entries key_hash = key.hash index = key_hash & @mask # key_index key_hash entry = @entries[index] unless entry @entries[index] = new_entry key, key_hash, value return value end if entry.match? key, key_hash return entry.value = value end last = entry entry = entry.next while entry if entry.match? key, key_hash return entry.value = value end last = entry entry = entry.next end last.next = new_entry key, key_hash, value value end alias_method :store, :[]= # Used internally to get around subclasses redefining #[]= alias_method :__store__, :[]= def clear setup self end def default(key = undefined) # current MRI documentation comment is wrong. Actual behavior is: # Hash.new { 1 }.default # => nil if @default_proc key.equal?(undefined) ? nil : @default.call(self, key) else @default end end def default=(value) @default_proc = false @default = value end def default_proc @default if @default_proc end def delete(key) key_hash = key.hash index = key_index key_hash if entry = @entries[index] if entry.match? key, key_hash @entries[index] = entry.next @size -= 1 return entry.value end last = entry while entry = entry.next if entry.match? key, key_hash last.next = entry.next @size -= 1 return entry.value end last = entry end end return yield(key) if block_given? end def delete_if(&block) return to_enum :delete_if unless block_given? select(&block).each { |k, v| delete k } self end def each return to_enum :each unless block_given? i = to_iter while entry = i.next(entry) yield [entry.key, entry.value] end self end def each_key return to_enum :each_key unless block_given? i = to_iter while entry = i.next(entry) yield entry.key end self end def each_pair return to_enum :each_pair unless block_given? i = to_iter while entry = i.next(entry) yield entry.key, entry.value end self end def each_value return to_enum :each_value unless block_given? i = to_iter while entry = i.next(entry) yield entry.value end self end # Returns true if there are no entries. def empty? @size == 0 end def fetch(key, default = undefined) if entry = find_entry(key) return entry.value end return yield(key) if block_given? return default unless default.equal?(undefined) raise IndexError, 'key not found' end # Searches for an entry matching +key+. Returns the entry # if found. Otherwise returns +nil+. def find_entry(key) key_hash = key.hash entry = @entries[key_index(key_hash)] while entry if entry.match? key, key_hash return entry end entry = entry.next end end private :find_entry def index(value) i = to_iter while entry = i.next(entry) return entry.key if entry.value == value end nil end def initialize(default = undefined, &block) if !default.equal?(undefined) and block raise ArgumentError, "Specify a default or a block, not both" end if block @default = block @default_proc = true elsif !default.equal?(undefined) @default = default @default_proc = false end end private :initialize def initialize_copy(other) replace other end private :initialize_copy def inspect out = [] return '{...}' if Thread.detect_recursion self do i = to_iter while entry = i.next(entry) str = entry.key.inspect str << '=>' str << entry.value.inspect out << str end end "{#{out.join ', '}}" end def invert inverted = {} i = to_iter while entry = i.next(entry) inverted[entry.value] = entry.key end inverted end def key?(key) find_entry(key) != nil end alias_method :has_key?, :key? alias_method :include?, :key? alias_method :member?, :key? # Calculates the +@entries+ slot given a key_hash value. def key_index(key_hash) key_hash & @mask end private :key_index def keys map { |key, value| key } end def merge(other, &block) dup.merge!(other, &block) end def merge!(other) other = Type.coerce_to other, Hash, :to_hash i = other.to_iter while entry = i.next(entry) key = entry.key if block_given? and key? key self.__store__ key, yield(key, self[key], entry.value) else self.__store__ key, entry.value end end self end alias_method :update, :merge! # Returns a new +Entry+ instance having +key+, +key_hash+, # and +value+. If +key+ is a kind of +String+, +key+ is # duped and frozen. def new_entry(key, key_hash, value) if key.kind_of? String key = key.dup key.freeze end @size += 1 Entry.new key, key_hash, value end private :new_entry # Adjusts the hash storage and redistributes the entries among # the new bins. Any Iterator instance will be invalid after a # call to #redistribute. Does not recalculate the cached key_hash # values. See +#rehash+. def redistribute(entries) capacity = @capacity # TODO: grow smaller too setup @capacity * 2, @max_entries * 2, @size i = -1 while (i += 1) < capacity next unless old = entries[i] while old old.next = nil if nxt = old.next index = key_index old.key_hash if entry = @entries[index] old.next = entry end @entries[index] = old old = nxt end end end # Recalculates the cached key_hash values and reorders the entries # into a new +@entries+ vector. Does NOT change the size of the # hash. See +#redistribute+. def rehash capacity = @capacity entries = @entries @entries = Entries.new @capacity i = -1 while (i += 1) < capacity next unless old = entries[i] while old old.next = nil if nxt = old.next index = key_index(old.key_hash = old.key.hash) if entry = @entries[index] old.next = entry end @entries[index] = old old = nxt end end self end def reject(&block) return to_enum :reject unless block_given? hsh = dup hsh.reject! &block hsh end def reject! return to_enum :reject! unless block_given? rejected = select { |k, v| yield k, v } return if rejected.empty? rejected.each { |k, v| delete k } self end def replace(other) other = Type.coerce_to other, Hash, :to_hash return self if self.equal? other setup i = other.to_iter while entry = i.next(entry) __store__ entry.key, entry.value end if other.default_proc @default = other.default_proc @default_proc = true else @default = other.default @default_proc = false end self end def select return to_enum :select unless block_given? selected = [] i = to_iter while entry = i.next(entry) if yield(entry.key, entry.value) selected << [entry.key, entry.value] end end selected end def shift return default(nil) if empty? i = to_iter if entry = i.next(entry) @entries[i.index] = entry.next @size -= 1 return entry.key, entry.value end end # packed! [:@capacity, :@mask, :@max_entries, :@size, :@entries] # Sets the underlying data structures. # # @capacity is the maximum number of +@entries+. # @max_entries is the maximum number of entries before redistributing. # @size is the number of pairs, equivalent to <code>hsh.size</code>. # @entrien is the vector of storage for the entry chains. def setup(capacity=MIN_SIZE, max=MAX_ENTRIES, size=0) @capacity = capacity @mask = capacity - 1 @max_entries = max @size = size @entries = Entries.new capacity end private :setup def sort(&block) to_a.sort(&block) end def to_a select { true } end # Returns an external iterator for the bins. See +Iterator+ def to_iter Iterator.new @entries, @capacity end def to_hash self end def to_s to_a.join end def value?(value) i = to_iter while entry = i.next(entry) return true if entry.value == value end false end alias_method :has_value?, :value? def values map { |key, value| value } end def values_at(*args) args.collect { |key| self[key] } end alias_method :indexes, :values_at alias_method :indices, :values_at end
# -*- encoding: us-ascii -*- class Proc def self.__from_block__(env) Rubinius.primitive :proc_from_env if Rubinius::Type.object_kind_of? env, Rubinius::BlockEnvironment raise PrimitiveFailure, "Proc.__from_block__ primitive failed to create Proc from BlockEnvironment" else begin env.to_proc rescue Exception raise ArgumentError, "Unable to convert #{env.inspect} to a Proc" end end end def self.new(*args) env = nil Rubinius.asm do push_block # assign a pushed block to the above local variable "env" set_local 1 end unless env # Support for ancient pre-block-pass style: # def something; Proc.new; end # something { a_block } => Proc instance env = Rubinius::BlockEnvironment.of_sender unless env raise ArgumentError, "tried to create a Proc object without a block" end end block = __from_block__(env) if block.class != self and block.class != Method block = block.dup Rubinius::Unsafe.set_class(block, self) end Rubinius.asm(block, args) do |b, a| run b run a run b send_with_splat :initialize, 0, true end return block end attr_accessor :block def binding bind = @block.to_binding bind.proc_environment = @block bind end def ==(other) return false unless other.kind_of? self.class @block == other.block end def arity if @bound_method arity = @bound_method.arity return arity < 0 ? -1 : arity end @block.arity end def parameters if @bound_method return @bound_method.parameters end code = @block.compiled_code return [] unless code.respond_to? :local_names m = code.required_args - code.post_args o = m + code.total_args - code.required_args p = o + code.post_args p += 1 if code.splat required_status = self.lambda? ? :req : :opt code.local_names.each_with_index.map do |name, i| if i < m [required_status, name] elsif i < o [:opt, name] elsif code.splat == i name == :@unnamed_splat ? [:rest] : [:rest, name] elsif i < p [required_status, name] else [:block, name] end end end def to_proc self end alias_method :[], :call alias_method :yield, :call def clone copy = self.class.__allocate__ Rubinius.invoke_primitive :object_copy_object, copy, self Rubinius.invoke_primitive :object_copy_singleton_class, copy, self Rubinius.privately do copy.initialize_copy self end copy.freeze if frozen? copy end def dup copy = self.class.__allocate__ Rubinius.invoke_primitive :object_copy_object, copy, self Rubinius.privately do copy.initialize_copy self end copy end class Method < Proc attr_accessor :bound_method def call(*args, &block) @bound_method.call(*args, &block) end alias_method :[], :call def self.new(meth) if meth.kind_of? ::Method return __from_method__(meth) else raise ArgumentError, "tried to create a Proc::Method object without a Method" end end def inspect code = @bound_method.executable if code.respond_to? :file if code.lines line = code.first_line else line = "-1" end file = code.file else line = "-1" file = "(unknown)" end "#<#{self.class}:0x#{self.object_id.to_s(16)} @ #{file}:#{line}>" end alias_method :to_s, :inspect def ==(other) return false unless other.kind_of? self.class @bound_method == other.bound_method end def arity @bound_method.arity end end end Also consider @bound_method for equality # -*- encoding: us-ascii -*- class Proc def self.__from_block__(env) Rubinius.primitive :proc_from_env if Rubinius::Type.object_kind_of? env, Rubinius::BlockEnvironment raise PrimitiveFailure, "Proc.__from_block__ primitive failed to create Proc from BlockEnvironment" else begin env.to_proc rescue Exception raise ArgumentError, "Unable to convert #{env.inspect} to a Proc" end end end def self.new(*args) env = nil Rubinius.asm do push_block # assign a pushed block to the above local variable "env" set_local 1 end unless env # Support for ancient pre-block-pass style: # def something; Proc.new; end # something { a_block } => Proc instance env = Rubinius::BlockEnvironment.of_sender unless env raise ArgumentError, "tried to create a Proc object without a block" end end block = __from_block__(env) if block.class != self and block.class != Method block = block.dup Rubinius::Unsafe.set_class(block, self) end Rubinius.asm(block, args) do |b, a| run b run a run b send_with_splat :initialize, 0, true end return block end attr_accessor :block attr_accessor :bound_method def binding bind = @block.to_binding bind.proc_environment = @block bind end def ==(other) return false unless other.kind_of? self.class @block == other.block and @bound_method == other.bound_method end def arity if @bound_method arity = @bound_method.arity return arity < 0 ? -1 : arity end @block.arity end def parameters if @bound_method return @bound_method.parameters end code = @block.compiled_code return [] unless code.respond_to? :local_names m = code.required_args - code.post_args o = m + code.total_args - code.required_args p = o + code.post_args p += 1 if code.splat required_status = self.lambda? ? :req : :opt code.local_names.each_with_index.map do |name, i| if i < m [required_status, name] elsif i < o [:opt, name] elsif code.splat == i name == :@unnamed_splat ? [:rest] : [:rest, name] elsif i < p [required_status, name] else [:block, name] end end end def to_proc self end alias_method :[], :call alias_method :yield, :call def clone copy = self.class.__allocate__ Rubinius.invoke_primitive :object_copy_object, copy, self Rubinius.invoke_primitive :object_copy_singleton_class, copy, self Rubinius.privately do copy.initialize_copy self end copy.freeze if frozen? copy end def dup copy = self.class.__allocate__ Rubinius.invoke_primitive :object_copy_object, copy, self Rubinius.privately do copy.initialize_copy self end copy end class Method < Proc attr_accessor :bound_method def call(*args, &block) @bound_method.call(*args, &block) end alias_method :[], :call def self.new(meth) if meth.kind_of? ::Method return __from_method__(meth) else raise ArgumentError, "tried to create a Proc::Method object without a Method" end end def inspect code = @bound_method.executable if code.respond_to? :file if code.lines line = code.first_line else line = "-1" end file = code.file else line = "-1" file = "(unknown)" end "#<#{self.class}:0x#{self.object_id.to_s(16)} @ #{file}:#{line}>" end alias_method :to_s, :inspect def ==(other) return false unless other.kind_of? self.class @bound_method == other.bound_method end def arity @bound_method.arity end end end
module Admino VERSION = "0.0.4" end Upversion module Admino VERSION = "0.0.5" end
module Adrian VERSION = '1.3.2' end Release v1.3.3 module Adrian VERSION = '1.3.3' end
module Airenv VERSION = "0.0.1" end Bumps to version 0.0.3 module Airenv VERSION = "0.0.3" end
require 'net/http' require 'cgi' module Akismet # A Ruby client for the Akismet API. # # @example # # # Verify an API key # # # # Akismet::Client.new( 'apikey123', 'http://jonahb.com' ).verify_key # # @example # # # Check whether a comment is spam # # # # client = Akismet::Client.new( 'apikey123', # 'http://jonahb.com', # :app_name => 'jonahb.com', # :app_version => '1.0' ) # # # assumes variables comment, post_url, request (a racklike HTTP request) # spam = client.comment_check( request.remote_ip, # request.user_agent, # :content_type => 'comment', # :referrer => request.headers[ 'HTTP_REFERER' ], # :permalink => post_url, # :comment_author => comment.author, # :comment_author_email => comment.author_email, # :comment_content => comment.body ) # # if spam # # ... # end # # @example # # # Submit a batch of checks using a single TCP connection # # # # # client = Akismet::Client.new( 'apikey123', # 'http://jonahb.com', # :app_name => 'jonahb.com', # :app_version => '1.0' ) # # begin # client.open # comments.each do |comment| # client.comment_check( ... ) # see example above # end # ensure # client.close # end # # # ... or ... # # Akismet::Client.open( 'apikey123', # 'http://jonahb.com', # :app_name => 'jonahb.com', # :app_version => '1.0' ) do |client| # comments.each do |comment| # client.comment_check( ... ) # see example above # end # end # # class Client # The API key obtained at akismet.com. # @return [String] attr_reader :api_key # The URL of the home page of the application making the request. # @return [String] attr_reader :home_url # The name of the application making the request, e.g "jonahb.com". # @return [String] attr_reader :app_name # The version of the application making the request, e.g. "1.0". # @return [String] attr_reader :app_version #@!group Constructors # @param [String] api_key # The API key obtained at akismet.com. # @param [String] home_url # The URL of the home page of the application making the request. # @option options [String] :app_name # The name of the application making the request, e.g. "jonahb.com". # Forms part of the User-Agent header submitted to Akismet. # @option options [String] :app_version # The version of the application making the request, e.g. "1.0". Forms # part of the User-Agent header submitted to Akismet. Ignored if # :app_name is not privded. # def initialize( api_key, home_url, options = {} ) @api_key = api_key @home_url = home_url @app_name = options[ :app_name ] @app_version = options[ :app_version ] @http_session = nil end #@!group Sessions # Initializes a client, opens it, yields it to the given block, and closes # it when the block returns. # @param (see #initialize) # @option (see #initialize) # @yieldparam [Client] client # @return [Client] # @see #open # def self.open(api_key, home_url, options = {}) raise "Block required" unless block_given? client = new(api_key, home_url) client.open { yield client } client end # Opens the client, creating a new TCP connection. # # If a block is given, yields to the block, closes the client when the # block returns, and returns the return value of the block. If a # block is not given, returns self and leaves the client open, relying on # the caller to close the client with {#close}. # # Note that opening and closing the client is only required if you want to # make several calls under one TCP connection. Otherwise, you can simply # call {#comment_check}, {#submit_ham}, or {#submit_spam}, which call # {#open} for you if necessary. # # Due to a peculiarity of the Akismet API, {#verify_key} always creates its # own connection. # # @yield # If a block is given, the client is closed when the block returns. # @return [Object, self] # If a block is given, the return value of the block; otherwise, +self+. # @raise [StandardError] # The client is already open # def open raise "Already open" if open? @http_session = Net::HTTP.new( "#{ api_key }.rest.akismet.com", 80 ) begin @http_session.start block_given? ? yield : self ensure close if block_given? end end # Closes the Client. # @return [self] # @see #open # def close @http_session.finish if open? @http_session = nil self end # Whether the Client is open. # @return [Boolean] # def open? @http_session && @http_session.started? end #@!group Akismet API # Checks the validity of the API key. # @return [Boolean] # def verify_key response = Net::HTTP.start( 'rest.akismet.com', 80 ) do |session| invoke( session, 'verify-key', :blog => home_url, :key => api_key ) end unless %w{ valid invalid }.include?( response.body ) raise_with_response response end response.body == 'valid' end # Checks whether a comment is spam. You are encouraged the submit, in # addition to the documented parameters, data about the client and the # comment submission. For example, if the client is an HTTP server, # include HTTP headers and environment variables. # # If the Client is not open, opens it for the duration of the call. # # @return [Boolean] # @raise [Akismet::Error] # @param [String] user_ip # The IP address of the submitter of the comment. # @param [String] user_agent # The user agent of the web browser submitting the comment. Typically # the HTTP_USER_AGENT CGI variable. Not to be confused with the user # agent of the Akismet library. # @option params [String] :referrer # The value of the HTTP_REFERER header. Note that the parameter is # spelled with two consecutive 'r's. # @option params [String] :permalink # The permanent URL of the entry to which the comment pertains. # @option params [String] :comment_type # 'comment', 'trackback', 'pingback', or a made-up value like # 'registration' # @option params [String] :comment_author # The name of the author of the comment. # @option params [String] :comment_author_email # The email address of the author of the comment. # @option params [String] :comment_author_url # A URL submitted with the comment. # @option params [String] :comment_content # The text of the comment. # def check( user_ip, user_agent, params = {} ) response = invoke_comment_method( 'comment-check', user_ip, user_agent, params ) unless %w{ true false }.include?( response.body ) raise_with_response response end response.body == 'true' end alias_method :comment_check, :check # Submits a comment that has been identified as not-spam (ham). If the # Client is not open, opens it for the duration of the call. # # @param (see #check) # @option (see #check) # @return [void] # @raise (see #check) # def ham( user_ip, user_agent, params = {} ) response = invoke_comment_method( 'submit-ham', user_ip, user_agent, params ) unless response.body == 'Thanks for making the web a better place.' raise_with_response response end end alias_method :submit_ham, :ham # Submits a comment that has been identified as spam. If the Client is not # open, opens it for the duration of the call. # # @param (see #check) # @option (see #check) # @return [void] # @raise (see #check) # def spam( user_ip, user_agent, params = {} ) response = invoke_comment_method( 'submit-spam', user_ip, user_agent, params ) unless response.body == 'Thanks for making the web a better place.' raise_with_response response end end alias_method :submit_spam, :spam private # Yields an HTTP session to the given block. Uses this instance's open # session if any; otherwise opens one and closes it when the block # returns. # @yield [Net::HTTP] # def in_http_session if open? yield @http_session else open { yield @http_session } end end # Raises an error given a response. The Akismet documentation states that # the HTTP headers of the response may contain error strings. I can't # seem to find them, so for now just raise an unknown error. # @param [Net::HTTPResponse] response # def raise_with_response( response ) raise Error.new( Error::UNKNOWN, 'Unknown error' ) end # @param [String] method_name # @param [String] user_ip # @param [String] user_agent # @param [Hash] params # @return [Net::HTTPResponse] # @raise [Akismet::Error] # The API key is invalid. # def invoke_comment_method( method_name, user_ip, user_agent, params = {} ) params = params.merge :blog => home_url, :user_ip => user_ip, :user_agent => user_agent response = in_http_session do |session| invoke( session, method_name, params ) end if response.body == 'invalid' raise Error.new( Error::INVALID_API_KEY, 'Invalid API key' ) end response end # @param [Net::HTTP] http_session # A started HTTP session # @param [String] method_name # @return [Net::HTTPResponse] # @raise [Akismet::Error] # An HTTP response other than 200 is received. # def invoke( http_session, method_name, params = {} ) response = http_session.post( "/1.1/#{ method_name }", url_encode( params ), http_headers ) unless response.is_a?( Net::HTTPOK ) raise Error, "HTTP #{ response.code } received (expected 200)" end response end # @return [Hash] def http_headers { 'User-Agent' => user_agent, 'Content-Type' => 'application/x-www-form-urlencoded' } end # @return [String] def url_encode( hash = {} ) hash.collect do |k, v| "#{ CGI.escape( k.to_s ) }=#{ CGI.escape( v.to_s ) }" end.join( "&" ) end # From the Akismet documentation: # If possible, your user agent string should always use the following # format: Application Name/Version | Plugin Name/Version # @return [String] # def user_agent [ user_agent_app, user_agent_plugin ].compact.join( " | " ) end # Returns nil if the Client was instantiated without an app_name. # @return [String] # def user_agent_app app_name && [ app_name, app_version ].compact.join( "/" ) end # @return [String] def user_agent_plugin "Ruby Akismet/#{ Akismet::VERSION }" end end end Use short method aliases in documentation for Client#open require 'net/http' require 'cgi' module Akismet # A Ruby client for the Akismet API. # # @example # # # Verify an API key # # # # Akismet::Client.new( 'apikey123', 'http://jonahb.com' ).verify_key # # @example # # # Check whether a comment is spam # # # # client = Akismet::Client.new( 'apikey123', # 'http://jonahb.com', # :app_name => 'jonahb.com', # :app_version => '1.0' ) # # # assumes variables comment, post_url, request (a racklike HTTP request) # spam = client.comment_check( request.remote_ip, # request.user_agent, # :content_type => 'comment', # :referrer => request.headers[ 'HTTP_REFERER' ], # :permalink => post_url, # :comment_author => comment.author, # :comment_author_email => comment.author_email, # :comment_content => comment.body ) # # if spam # # ... # end # # @example # # # Submit a batch of checks using a single TCP connection # # # # # client = Akismet::Client.new( 'apikey123', # 'http://jonahb.com', # :app_name => 'jonahb.com', # :app_version => '1.0' ) # # begin # client.open # comments.each do |comment| # client.comment_check( ... ) # see example above # end # ensure # client.close # end # # # ... or ... # # Akismet::Client.open( 'apikey123', # 'http://jonahb.com', # :app_name => 'jonahb.com', # :app_version => '1.0' ) do |client| # comments.each do |comment| # client.comment_check( ... ) # see example above # end # end # # class Client # The API key obtained at akismet.com. # @return [String] attr_reader :api_key # The URL of the home page of the application making the request. # @return [String] attr_reader :home_url # The name of the application making the request, e.g "jonahb.com". # @return [String] attr_reader :app_name # The version of the application making the request, e.g. "1.0". # @return [String] attr_reader :app_version #@!group Constructors # @param [String] api_key # The API key obtained at akismet.com. # @param [String] home_url # The URL of the home page of the application making the request. # @option options [String] :app_name # The name of the application making the request, e.g. "jonahb.com". # Forms part of the User-Agent header submitted to Akismet. # @option options [String] :app_version # The version of the application making the request, e.g. "1.0". Forms # part of the User-Agent header submitted to Akismet. Ignored if # :app_name is not privded. # def initialize( api_key, home_url, options = {} ) @api_key = api_key @home_url = home_url @app_name = options[ :app_name ] @app_version = options[ :app_version ] @http_session = nil end #@!group Sessions # Initializes a client, opens it, yields it to the given block, and closes # it when the block returns. # @param (see #initialize) # @option (see #initialize) # @yieldparam [Client] client # @return [Client] # @see #open # def self.open(api_key, home_url, options = {}) raise "Block required" unless block_given? client = new(api_key, home_url) client.open { yield client } client end # Opens the client, creating a new TCP connection. # # If a block is given, yields to the block, closes the client when the # block returns, and returns the return value of the block. If a # block is not given, returns self and leaves the client open, relying on # the caller to close the client with {#close}. # # Note that opening and closing the client is only required if you want to # make several calls under one TCP connection. Otherwise, you can simply # call {#check}, {#ham}, or {#spam}, which call {#open} for you if # necessary. # # Due to a peculiarity of the Akismet API, {#verify_key} always creates its # own connection. # # @yield # If a block is given, the client is closed when the block returns. # @return [Object, self] # If a block is given, the return value of the block; otherwise, +self+. # @raise [StandardError] # The client is already open # def open raise "Already open" if open? @http_session = Net::HTTP.new( "#{ api_key }.rest.akismet.com", 80 ) begin @http_session.start block_given? ? yield : self ensure close if block_given? end end # Closes the Client. # @return [self] # @see #open # def close @http_session.finish if open? @http_session = nil self end # Whether the Client is open. # @return [Boolean] # def open? @http_session && @http_session.started? end #@!group Akismet API # Checks the validity of the API key. # @return [Boolean] # def verify_key response = Net::HTTP.start( 'rest.akismet.com', 80 ) do |session| invoke( session, 'verify-key', :blog => home_url, :key => api_key ) end unless %w{ valid invalid }.include?( response.body ) raise_with_response response end response.body == 'valid' end # Checks whether a comment is spam. You are encouraged the submit, in # addition to the documented parameters, data about the client and the # comment submission. For example, if the client is an HTTP server, # include HTTP headers and environment variables. # # If the Client is not open, opens it for the duration of the call. # # @return [Boolean] # @raise [Akismet::Error] # @param [String] user_ip # The IP address of the submitter of the comment. # @param [String] user_agent # The user agent of the web browser submitting the comment. Typically # the HTTP_USER_AGENT CGI variable. Not to be confused with the user # agent of the Akismet library. # @option params [String] :referrer # The value of the HTTP_REFERER header. Note that the parameter is # spelled with two consecutive 'r's. # @option params [String] :permalink # The permanent URL of the entry to which the comment pertains. # @option params [String] :comment_type # 'comment', 'trackback', 'pingback', or a made-up value like # 'registration' # @option params [String] :comment_author # The name of the author of the comment. # @option params [String] :comment_author_email # The email address of the author of the comment. # @option params [String] :comment_author_url # A URL submitted with the comment. # @option params [String] :comment_content # The text of the comment. # def check( user_ip, user_agent, params = {} ) response = invoke_comment_method( 'comment-check', user_ip, user_agent, params ) unless %w{ true false }.include?( response.body ) raise_with_response response end response.body == 'true' end alias_method :comment_check, :check # Submits a comment that has been identified as not-spam (ham). If the # Client is not open, opens it for the duration of the call. # # @param (see #check) # @option (see #check) # @return [void] # @raise (see #check) # def ham( user_ip, user_agent, params = {} ) response = invoke_comment_method( 'submit-ham', user_ip, user_agent, params ) unless response.body == 'Thanks for making the web a better place.' raise_with_response response end end alias_method :submit_ham, :ham # Submits a comment that has been identified as spam. If the Client is not # open, opens it for the duration of the call. # # @param (see #check) # @option (see #check) # @return [void] # @raise (see #check) # def spam( user_ip, user_agent, params = {} ) response = invoke_comment_method( 'submit-spam', user_ip, user_agent, params ) unless response.body == 'Thanks for making the web a better place.' raise_with_response response end end alias_method :submit_spam, :spam private # Yields an HTTP session to the given block. Uses this instance's open # session if any; otherwise opens one and closes it when the block # returns. # @yield [Net::HTTP] # def in_http_session if open? yield @http_session else open { yield @http_session } end end # Raises an error given a response. The Akismet documentation states that # the HTTP headers of the response may contain error strings. I can't # seem to find them, so for now just raise an unknown error. # @param [Net::HTTPResponse] response # def raise_with_response( response ) raise Error.new( Error::UNKNOWN, 'Unknown error' ) end # @param [String] method_name # @param [String] user_ip # @param [String] user_agent # @param [Hash] params # @return [Net::HTTPResponse] # @raise [Akismet::Error] # The API key is invalid. # def invoke_comment_method( method_name, user_ip, user_agent, params = {} ) params = params.merge :blog => home_url, :user_ip => user_ip, :user_agent => user_agent response = in_http_session do |session| invoke( session, method_name, params ) end if response.body == 'invalid' raise Error.new( Error::INVALID_API_KEY, 'Invalid API key' ) end response end # @param [Net::HTTP] http_session # A started HTTP session # @param [String] method_name # @return [Net::HTTPResponse] # @raise [Akismet::Error] # An HTTP response other than 200 is received. # def invoke( http_session, method_name, params = {} ) response = http_session.post( "/1.1/#{ method_name }", url_encode( params ), http_headers ) unless response.is_a?( Net::HTTPOK ) raise Error, "HTTP #{ response.code } received (expected 200)" end response end # @return [Hash] def http_headers { 'User-Agent' => user_agent, 'Content-Type' => 'application/x-www-form-urlencoded' } end # @return [String] def url_encode( hash = {} ) hash.collect do |k, v| "#{ CGI.escape( k.to_s ) }=#{ CGI.escape( v.to_s ) }" end.join( "&" ) end # From the Akismet documentation: # If possible, your user agent string should always use the following # format: Application Name/Version | Plugin Name/Version # @return [String] # def user_agent [ user_agent_app, user_agent_plugin ].compact.join( " | " ) end # Returns nil if the Client was instantiated without an app_name. # @return [String] # def user_agent_app app_name && [ app_name, app_version ].compact.join( "/" ) end # @return [String] def user_agent_plugin "Ruby Akismet/#{ Akismet::VERSION }" end end end
THEME_DIR = File.expand_path("../..", __FILE__) ALAVETELI_DIR = File.expand_path("../../../", THEME_DIR) THEME_NAME = File.split(THEME_DIR)[1] class ActionController::Base # The following prepends the path of the current theme's views to # the "filter_path" that Rails searches when deciding which # template to use for a view. It does so by creating a method # uniquely named for this theme. path_function_name = "set_view_paths_for_#{THEME_NAME}" before_filter path_function_name.to_sym send :define_method, path_function_name do self.prepend_view_path File.join(File.dirname(__FILE__), "views") end end # In order to have the theme lib/ folder ahead of the main app one, # inspired in Ruby Guides explanation: http://guides.rubyonrails.org/plugins.html %w{ . }.each do |dir| path = File.join(File.dirname(__FILE__), dir) $LOAD_PATH.insert(0, path) ActiveSupport::Dependencies.autoload_paths << path ActiveSupport::Dependencies.autoload_once_paths.delete(path) end # Monkey patch app code for patch in ['controller_patches.rb', 'model_patches.rb', 'patch_mailer_paths.rb', 'config/custom-routes.rb', 'gettext_setup.rb'] require File.expand_path "../#{patch}", __FILE__ end # migration-type stuff # if not already created, make a CensorRule that hides personal information regexp = '([^=]*)={8,}.*\n(?:.*?#.*?: ?.*\n){3,}.*={8,}' rule = CensorRule.find_by_text(regexp) if rule.nil? Rails.logger.info("Creating new censor rule: /#{regexp}/") CensorRule.create(:text => regexp, :replacement => '\1[redacted]', :regexp => true, :last_edit_editor => 'system', :last_edit_comment => 'Added automatically by ipvtheme') end # DOB and address for users def column_exists?(table, column) # XXX ActiveRecord 3 includes "column_exists?" method on `connection` return ActiveRecord::Base.connection.columns(table.to_sym).collect{|c| c.name.to_sym}.include? column end if !column_exists?(:users, :dob) || !column_exists?(:users, :address) require 'db/migrate/ipvtheme_add_address_and_dob_to_user' IpvthemeAddAddressAndDobToUser.up end Use new way of setting custom routes THEME_DIR = File.expand_path("../..", __FILE__) ALAVETELI_DIR = File.expand_path("../../../", THEME_DIR) THEME_NAME = File.split(THEME_DIR)[1] class ActionController::Base # The following prepends the path of the current theme's views to # the "filter_path" that Rails searches when deciding which # template to use for a view. It does so by creating a method # uniquely named for this theme. path_function_name = "set_view_paths_for_#{THEME_NAME}" before_filter path_function_name.to_sym send :define_method, path_function_name do self.prepend_view_path File.join(File.dirname(__FILE__), "views") end end # In order to have the theme lib/ folder ahead of the main app one, # inspired in Ruby Guides explanation: http://guides.rubyonrails.org/plugins.html %w{ . }.each do |dir| path = File.join(File.dirname(__FILE__), dir) $LOAD_PATH.insert(0, path) ActiveSupport::Dependencies.autoload_paths << path ActiveSupport::Dependencies.autoload_once_paths.delete(path) end # Monkey patch app code for patch in ['controller_patches.rb', 'model_patches.rb', 'patch_mailer_paths.rb', 'gettext_setup.rb'] require File.expand_path "../#{patch}", __FILE__ end $alaveteli_route_extensions << 'custom-routes.rb' # migration-type stuff # if not already created, make a CensorRule that hides personal information regexp = '([^=]*)={8,}.*\n(?:.*?#.*?: ?.*\n){3,}.*={8,}' rule = CensorRule.find_by_text(regexp) if rule.nil? Rails.logger.info("Creating new censor rule: /#{regexp}/") CensorRule.create(:text => regexp, :replacement => '\1[redacted]', :regexp => true, :last_edit_editor => 'system', :last_edit_comment => 'Added automatically by ipvtheme') end # DOB and address for users def column_exists?(table, column) # XXX ActiveRecord 3 includes "column_exists?" method on `connection` return ActiveRecord::Base.connection.columns(table.to_sym).collect{|c| c.name.to_sym}.include? column end if !column_exists?(:users, :dob) || !column_exists?(:users, :address) require 'db/migrate/ipvtheme_add_address_and_dob_to_user' IpvthemeAddAddressAndDobToUser.up end
module Amistad class << self attr_accessor :friend_model def configure yield self end def friend_model @friend_model || 'User' end def friendship_model "#{self.friend_model}Friendship" end def friendship_class Amistad::Friendships.const_get(self.friendship_model) end end end Add support to namespaced friend model This commit only removes the unecessary dependency of model naming. It's uneeded to have a friendship_model dependent on friend_model's name, since it brings problems with namespaced models (e.g. 'User::Profile'). module Amistad class << self attr_accessor :friend_model def configure yield self end def friend_model @friend_model || 'User' end def friendship_model "Friendship" end def friendship_class Amistad::Friendships::Friendship end end end
module Analytical module Modules class DummyModule include Analytical::Modules::Base def method_missing(method, *args, &block); nil; end end end class Api attr_accessor :options, :modules def initialize(options={}) @options = options @modules = @options[:modules].inject(ActiveSupport::OrderedHash.new) do |h, m| module_options = @options.merge(@options[m] || {}) module_options.delete(:modules) module_options[:session_store] = Analytical::SessionCommandStore.new(@options[:session], m) if @options[:session] h[m] = "Analytical::Modules::#{m.to_s.camelize}".constantize.new(module_options) h end @dummy_module = Analytical::Modules::DummyModule.new end # # Catch commands such as :track, :identify and send them on to all of the modules. # Or... if a module name is passed, return that module so it can be used directly, ie: # analytical.console.go 'make', :some=>:cookies # def method_missing(method, *args, &block) method = method.to_sym if @modules.keys.include?(method) @modules[method] elsif available_modules.include?(method) @dummy_module else process_command method, *args end end # # Delegation class that passes methods to # class ImmediateDelegateHelper def initialize(_parent) @parent = _parent end def method_missing(method, *args, &block) @parent.modules.values.collect do |m| m.send(method, *args) if m.respond_to?(method) end.compact.join("\n") end end # # Returns a new delegation object for immediate processing of a command # def now ImmediateDelegateHelper.new(self) end # # These methods return the javascript that should be inserted into each section of your layout # def head_prepend_javascript [init_javascript(:head_prepend), tracking_javascript(:head_prepend)].delete_if{|s| s.blank?}.join("\n") end def head_append_javascript [init_javascript(:head_append), tracking_javascript(:head_append)].delete_if{|s| s.blank?}.join("\n") end alias_method :head_javascript, :head_append_javascript def body_prepend_javascript [init_javascript(:body_prepend), tracking_javascript(:body_prepend)].delete_if{|s| s.blank?}.join("\n") end def body_append_javascript [init_javascript(:body_append), tracking_javascript(:body_append)].delete_if{|s| s.blank?}.join("\n") end private def process_command(command, *args) @modules.values.each do |m| m.queue command, *args end end def tracking_javascript(location) commands = [] @modules.each do |name, m| commands += m.process_queued_commands if m.init_location?(location) || m.initialized end commands = commands.delete_if{|c| c.blank? || c.empty?} unless commands.empty? commands.unshift "<script type='text/javascript'>" commands << "</script>" end commands.join("\n") end def init_javascript(location) @modules.values.collect do |m| m.init_javascript(location) end.compact.join("\n") end def available_modules Dir.glob(File.dirname(__FILE__)+'/modules/*.rb').collect do |f| File.basename(f).sub(/.rb/,'').to_sym end - [:base] end end end Bugfix, should test if module responds to #init_javascript module Analytical module Modules class DummyModule include Analytical::Modules::Base def method_missing(method, *args, &block); nil; end end end class Api attr_accessor :options, :modules def initialize(options={}) @options = options @modules = @options[:modules].inject(ActiveSupport::OrderedHash.new) do |h, m| module_options = @options.merge(@options[m] || {}) module_options.delete(:modules) module_options[:session_store] = Analytical::SessionCommandStore.new(@options[:session], m) if @options[:session] h[m] = "Analytical::Modules::#{m.to_s.camelize}".constantize.new(module_options) h end @dummy_module = Analytical::Modules::DummyModule.new end # # Catch commands such as :track, :identify and send them on to all of the modules. # Or... if a module name is passed, return that module so it can be used directly, ie: # analytical.console.go 'make', :some=>:cookies # def method_missing(method, *args, &block) method = method.to_sym if @modules.keys.include?(method) @modules[method] elsif available_modules.include?(method) @dummy_module else process_command method, *args end end # # Delegation class that passes methods to # class ImmediateDelegateHelper def initialize(_parent) @parent = _parent end def method_missing(method, *args, &block) @parent.modules.values.collect do |m| m.send(method, *args) if m.respond_to?(method) end.compact.join("\n") end end # # Returns a new delegation object for immediate processing of a command # def now ImmediateDelegateHelper.new(self) end # # These methods return the javascript that should be inserted into each section of your layout # def head_prepend_javascript [init_javascript(:head_prepend), tracking_javascript(:head_prepend)].delete_if{|s| s.blank?}.join("\n") end def head_append_javascript [init_javascript(:head_append), tracking_javascript(:head_append)].delete_if{|s| s.blank?}.join("\n") end alias_method :head_javascript, :head_append_javascript def body_prepend_javascript [init_javascript(:body_prepend), tracking_javascript(:body_prepend)].delete_if{|s| s.blank?}.join("\n") end def body_append_javascript [init_javascript(:body_append), tracking_javascript(:body_append)].delete_if{|s| s.blank?}.join("\n") end private def process_command(command, *args) @modules.values.each do |m| m.queue command, *args end end def tracking_javascript(location) commands = [] @modules.each do |name, m| commands += m.process_queued_commands if m.init_location?(location) || m.initialized end commands = commands.delete_if{|c| c.blank? || c.empty?} unless commands.empty? commands.unshift "<script type='text/javascript'>" commands << "</script>" end commands.join("\n") end def init_javascript(location) @modules.values.collect do |m| m.init_javascript(location) if m.respond_to?(:init_javascript) end.compact.join("\n") end def available_modules Dir.glob(File.dirname(__FILE__)+'/modules/*.rb').collect do |f| File.basename(f).sub(/.rb/,'').to_sym end - [:base] end end end
module Ansible class Runner class << self def run(env_vars, extra_vars, playbook_path) run_via_cli(env_vars, extra_vars, playbook_path) end private def run_via_cli(env_vars, extra_vars, playbook_path) result = AwesomeSpawn.run!(ansible_command, :env => env_vars, :params => [{:extra_vars => JSON.dump(extra_vars)}, playbook_path]) JSON.parse(result.output) end def ansible_command # TODO add possibility to use custom path, e.g. from virtualenv "ansible-playbook" end end end end Add a method to queue an Ansible::Runner.run This adds a way to queue an Ansible::Runner.run and wraps it in a task so that it can be invoked asynchronously from automate. module Ansible class Runner class << self def run(env_vars, extra_vars, playbook_path) run_via_cli(env_vars, extra_vars, playbook_path) end def run_queue(env_vars, extra_vars, playbook_path, user_id, queue_opts) queue_opts = { :args => [env_vars, extra_vars, playbook_path], :queue_name => "generic", :class_name => name, :method_name => "run", }.merge(queue_opts) task_opts = { :action => "Run Ansible Playbook", :userid => user_id, } MiqTask.generic_action_with_callback(task_opts, queue_opts) end private def run_via_cli(env_vars, extra_vars, playbook_path) result = AwesomeSpawn.run!(ansible_command, :env => env_vars, :params => [{:extra_vars => JSON.dump(extra_vars)}, playbook_path]) JSON.parse(result.output) end def ansible_command # TODO add possibility to use custom path, e.g. from virtualenv "ansible-playbook" end end end end
module Api2ch class Thread < Request def posts(board) posts = make_request(board) thread_list(posts) end private def thread_list(posts) arr = [] posts['threads'].map { |i| arr << i["num"] } post_list = arr.uniq.map(&:to_i) post_list.each do |num| @post_thread = [] # fix @board variable to dynamic variable @post_thread << HTTParty.get("#{BASE_URL}#{@board}/res/#{num}.json") end final = [] @post_thread.each do |res| final << JSON.parse(res.body) end end end end Fix thread module Api2ch class Thread < Request def posts(board) thread_list(board) end private def thread_list(board) posts = make_request(board) arr = [] posts['threads'].map { |i| arr << i["num"] } post_list = arr.uniq.map(&:to_i) post_list.each do |num| @post_thread = [] @post_thread << HTTParty.get("#{BASE_URL}#{board}/res/#{num}.json") end op_posts = [] @post_thread.each do |res| op_posts << JSON.parse(res.body) end end end end
require 'pg_query' module Aquel class Executor attr_reader :context def initialize @contexts = {} end def define(name, &block) @contexts[name] = Context.new(block) self end def execute(sql) ast = parser.parse(sql).parsetree.first type = ast['SELECT']['fromClause'][0]['RANGEVAR']['relname'] context = @contexts[type] context.execute! items = [] attributes = Attributes.new walk(ast['SELECT']['whereClause'], attributes) document = context.document_block.call(attributes.equal_values) if context.items_block context.items_block.call(document).each do |item| value = context.split_block.call(item) items << (value.kind_of?(Array) ? value : [value]) end elsif context.find_by_block.size > 0 context.find_by_block.each do |k, v| v.call(attributes.equal_values[k], document).each do |item| value = context.split_block.call(item) items << (value.kind_of?(Array) ? value : [value]) end end else while item = context.item_block.call(document) items << context.split_block.call(item) end end items = filter(items, attributes) items = colum_filter(items, ast['SELECT']['targetList']) end def filter(items, attributes) attributes.each do |k, v| if k.kind_of?(Fixnum) items = items.find_all do |item| v.operate(item[k-1]) end end end items end def colum_filter(items, target_list) items.map do |item| result = [] target_list.each do |target| val = expr_value(target['RESTARGET']['val']) case val when {"A_STAR"=>{}} result = item when Fixnum result << item[val-1] end end result end end def walk(node, attributes) if aexpr = node['AEXPR'] k = expr_value(aexpr['lexpr']) v = expr_value(aexpr['rexpr']) attributes[k] = Attribute.new(:value => v, :name => aexpr['name'][0]) elsif aexpr = node['AEXPR AND'] walk(aexpr['lexpr'], attributes) walk(aexpr['rexpr'], attributes) elsif aexpr['AEXPR OR'] raise 'OR clauses are not supported yet' end end def expr_value(expr) if expr['COLUMNREF'] expr['COLUMNREF']['fields'][0] elsif expr['A_CONST'] expr['A_CONST']['val'] end end def parser @parser ||= PgQuery end end end close opened document require 'pg_query' module Aquel class Executor attr_reader :context def initialize @contexts = {} end def define(name, &block) @contexts[name] = Context.new(block) self end def execute(sql) ast = parser.parse(sql).parsetree.first type = ast['SELECT']['fromClause'][0]['RANGEVAR']['relname'] context = @contexts[type] context.execute! items = [] attributes = Attributes.new walk(ast['SELECT']['whereClause'], attributes) document = context.document_block.call(attributes.equal_values) if context.items_block context.items_block.call(document).each do |item| value = context.split_block.call(item) items << (value.kind_of?(Array) ? value : [value]) end elsif context.find_by_block.size > 0 context.find_by_block.each do |k, v| v.call(attributes.equal_values[k], document).each do |item| value = context.split_block.call(item) items << (value.kind_of?(Array) ? value : [value]) end end else while item = context.item_block.call(document) items << context.split_block.call(item) end end items = filter(items, attributes) items = colum_filter(items, ast['SELECT']['targetList']) ensure if document.respond_to?(:close) document.close end end def filter(items, attributes) attributes.each do |k, v| if k.kind_of?(Fixnum) items = items.find_all do |item| v.operate(item[k-1]) end end end items end def colum_filter(items, target_list) items.map do |item| result = [] target_list.each do |target| val = expr_value(target['RESTARGET']['val']) case val when {"A_STAR"=>{}} result = item when Fixnum result << item[val-1] end end result end end def walk(node, attributes) if aexpr = node['AEXPR'] k = expr_value(aexpr['lexpr']) v = expr_value(aexpr['rexpr']) attributes[k] = Attribute.new(:value => v, :name => aexpr['name'][0]) elsif aexpr = node['AEXPR AND'] walk(aexpr['lexpr'], attributes) walk(aexpr['rexpr'], attributes) elsif aexpr['AEXPR OR'] raise 'OR clauses are not supported yet' end end def expr_value(expr) if expr['COLUMNREF'] expr['COLUMNREF']['fields'][0] elsif expr['A_CONST'] expr['A_CONST']['val'] end end def parser @parser ||= PgQuery end end end
module Arm class Translator # translator should translate from register instructio set to it's own (arm eg) # for each instruction we call the translator with translate_XXX # with XXX being the class name. # the result is replaced in the stream def translate instruction class_name = instruction.class.name.split("::").last self.send( "translate_#{class_name}".to_sym , instruction) end # don't replace labels def translate_Label code nil end # Arm stores the return address in a register (not on the stack) # The register is called link , or lr for short . # Maybe because it provides the "link" back to the caller # the vm defines a register for the location, so we store it there. def translate_SaveReturn code ArmMachine.str( :lr , code.register , 4 * code.index ) end def translate_GetSlot code # times 4 because arm works in bytes, but vm in words ArmMachine.ldr( code.register , code.array , 4 * code.index ) end def translate_RegisterTransfer code # Register machine convention is from => to # But arm has the receiver/result as the first ArmMachine.mov( code.to , code.from) end def translate_SetSlot code # times 4 because arm works in bytes, but vm in words ArmMachine.str( code.register , code.array , 4 * code.index ) end def translate_FunctionCall code ArmMachine.call( code.method ) end def translate_FunctionReturn code ArmMachine.ldr( :pc , code.register , 4 * code.index ) end def translate_LoadConstant code constant = code.constant if constant.is_a?(Parfait::Object) or constant.is_a? Symbol return ArmMachine.add( code.register , constant ) else return ArmMachine.mov( code.register , code.constant ) end end # This implements branch logic, which is simply assembler branch # # The only target for a call is a Block, so we just need to get the address for the code # and branch to it. def translate_Branch code ArmMachine.b( code.label ) end def translate_Syscall code call_codes = { :putstring => 4 , :exit => 1 } int_code = call_codes[code.name] raise "Not implemented syscall, #{code.name}" unless int_code send( code.name , int_code ) end def putstring int_code codes = ArmMachine.ldr( :r1 , Register.message_reg, 4 * Register.resolve_index(:message , :receiver)) codes.append ArmMachine.add( :r1 , :r1 , 8 ) codes.append ArmMachine.mov( :r0 , 1 ) codes.append ArmMachine.mov( :r2 , 12 ) # String length, obvious TODO syscall(int_code , codes ) end def exit int_code codes = Register::Label.new(nil , "exit") syscall int_code , codes end private # syscall is always triggered by swi(0) # The actual code (ie the index of the kernel function) is in r7 def syscall int_code , codes codes.append ArmMachine.mov( :r7 , int_code ) codes.append ArmMachine.swi( 0 ) codes end end end let labels be constants module Arm class Translator # translator should translate from register instructio set to it's own (arm eg) # for each instruction we call the translator with translate_XXX # with XXX being the class name. # the result is replaced in the stream def translate instruction class_name = instruction.class.name.split("::").last self.send( "translate_#{class_name}".to_sym , instruction) end # don't replace labels def translate_Label code nil end # Arm stores the return address in a register (not on the stack) # The register is called link , or lr for short . # Maybe because it provides the "link" back to the caller # the vm defines a register for the location, so we store it there. def translate_SaveReturn code ArmMachine.str( :lr , code.register , 4 * code.index ) end def translate_GetSlot code # times 4 because arm works in bytes, but vm in words ArmMachine.ldr( code.register , code.array , 4 * code.index ) end def translate_RegisterTransfer code # Register machine convention is from => to # But arm has the receiver/result as the first ArmMachine.mov( code.to , code.from) end def translate_SetSlot code # times 4 because arm works in bytes, but vm in words ArmMachine.str( code.register , code.array , 4 * code.index ) end def translate_FunctionCall code ArmMachine.call( code.method ) end def translate_FunctionReturn code ArmMachine.ldr( :pc , code.register , 4 * code.index ) end def translate_LoadConstant code constant = code.constant if constant.is_a?(Parfait::Object) or constant.is_a?(Symbol) or constant.is_a?(Register::Label) return ArmMachine.add( code.register , constant ) else return ArmMachine.mov( code.register , constant ) end end # This implements branch logic, which is simply assembler branch # # The only target for a call is a Block, so we just need to get the address for the code # and branch to it. def translate_Branch code ArmMachine.b( code.label ) end def translate_Syscall code call_codes = { :putstring => 4 , :exit => 1 } int_code = call_codes[code.name] raise "Not implemented syscall, #{code.name}" unless int_code send( code.name , int_code ) end def putstring int_code codes = ArmMachine.ldr( :r1 , Register.message_reg, 4 * Register.resolve_index(:message , :receiver)) codes.append ArmMachine.add( :r1 , :r1 , 8 ) codes.append ArmMachine.mov( :r0 , 1 ) codes.append ArmMachine.mov( :r2 , 12 ) # String length, obvious TODO syscall(int_code , codes ) end def exit int_code codes = Register::Label.new(nil , "exit") syscall int_code , codes end private # syscall is always triggered by swi(0) # The actual code (ie the index of the kernel function) is in r7 def syscall int_code , codes codes.append ArmMachine.mov( :r7 , int_code ) codes.append ArmMachine.swi( 0 ) codes end end end
require 'secure_random_string' module Authie class Session < ActiveRecord::Base # Errors which will be raised when there's an issue with a session's # validity in the request. class ValidityError < Error; end class InactiveSession < ValidityError; end class ExpiredSession < ValidityError; end class BrowserMismatch < ValidityError; end class HostMismatch < ValidityError; end class NoParentSessionForRevert < Error; end # Set table name self.table_name = "authie_sessions" # Relationships parent_options = {:class_name => "Authie::Session"} parent_options[:optional] = true if ActiveRecord::VERSION::MAJOR >= 5 belongs_to :parent, parent_options # Scopes scope :active, -> { where(:active => true) } scope :asc, -> { order(:last_activity_at => :desc) } scope :for_user, -> (user) { where(:user_type => user.class.to_s, :user_id => user.id) } # Attributes serialize :data, Hash attr_accessor :controller attr_accessor :temporary_token before_validation do if self.user_agent.is_a?(String) self.user_agent = self.user_agent[0,255] end if self.last_activity_path.is_a?(String) self.last_activity_path = self.last_activity_path[0,255] end end before_create do self.temporary_token = SecureRandomString.new(44) self.token_hash = self.class.hash_token(self.temporary_token) if controller self.user_agent = controller.request.user_agent set_cookie! end end before_destroy do cookies.delete(:user_session) if controller end # Return the user that def user if self.user_id && self.user_type @user ||= self.user_type.constantize.find_by(:id => self.user_id) || :none @user == :none ? nil : @user end end # This method should be called each time a user performs an # action while authenticated with this session. def touch! self.check_security! self.last_activity_at = Time.now self.last_activity_ip = controller.request.ip self.last_activity_path = controller.request.path self.requests += 1 self.save! Authie.config.events.dispatch(:session_touched, self) true end # Sets the cookie on the associated controller. def set_cookie! cookies[:user_session] = { :value => self.temporary_token, :secure => controller.request.ssl?, :httponly => true, :expires => self.expires_at } Authie.config.events.dispatch(:session_cookie_updated, self) true end # Check the security of the session to ensure it can be used. def check_security! if controller if cookies[:browser_id] != self.browser_id invalidate! Authie.config.events.dispatch(:browser_id_mismatch_error, self) raise BrowserMismatch, "Browser ID mismatch" end unless self.active? invalidate! Authie.config.events.dispatch(:invalid_session_error, self) raise InactiveSession, "Session is no longer active" end if self.expired? invalidate! Authie.config.events.dispatch(:expired_session_error, self) raise ExpiredSession, "Persistent session has expired" end if self.inactive? invalidate! Authie.config.events.dispatch(:inactive_session_error, self) raise InactiveSession, "Non-persistent session has expired" end if self.host && self.host != controller.request.host invalidate! Authie.config.events.dispatch(:host_mismatch_error, self) raise HostMismatch, "Session was created on #{self.host} but accessed using #{controller.request.host}" end end end # Has this persistent session expired? def expired? self.expires_at && self.expires_at < Time.now end # Has a non-persistent session become inactive? def inactive? self.expires_at.nil? && self.last_activity_at && self.last_activity_at < Authie.config.session_inactivity_timeout.ago end # Allow this session to persist rather than expiring at the end of the # current browser session def persist! self.expires_at = Authie.config.persistent_session_length.from_now self.save! set_cookie! end # Is this a persistent session? def persistent? !!expires_at end # Activate an old session def activate! self.active = true self.save! end # Mark this session as invalid def invalidate! self.active = false self.save! if controller cookies.delete(:user_session) end Authie.config.events.dispatch(:session_invalidated, self) true end # Set some additional data in this session def set(key, value) self.data ||= {} self.data[key.to_s] = value self.save! end # Get some additional data from this session def get(key) (self.data ||= {})[key.to_s] end # Invalidate all sessions but this one for this user def invalidate_others! self.class.where("id != ?", self.id).for_user(self.user).each do |s| s.invalidate! end end # Note that we have just seen the user enter their password. def see_password! self.password_seen_at = Time.now self.save! Authie.config.events.dispatch(:seen_password, self) true end # Have we seen the user's password recently in this sesion? def recently_seen_password? !!(self.password_seen_at && self.password_seen_at >= Authie.config.sudo_session_timeout.ago) end # Is two factor authentication required for this request? def two_factored? !!(two_factored_at || self.parent_id) end # Mark this request as two factor authoritsed def mark_as_two_factored! self.two_factored_at = Time.now self.two_factored_ip = controller.request.ip self.save! Authie.config.events.dispatch(:marked_as_two_factored, self) true end # Create a new session for impersonating for the given user def impersonate!(user) self.class.start(controller, :user => user, :parent => self) end # Revert back to the parent session def revert_to_parent! if self.parent self.invalidate! self.parent.activate! self.parent.controller = self.controller self.parent.set_cookie! self.parent else raise NoParentSessionForRevert, "Session does not have a parent therefore cannot be reverted." end end # Is this the first session for this session's browser? def first_session_for_browser? self.class.where("id < ?", self.id).for_user(self.user).where(:browser_id => self.browser_id).empty? end # Is this the first session for the IP? def first_session_for_ip? self.class.where("id < ?", self.id).for_user(self.user).where(:login_ip => self.login_ip).empty? end # Find a session from the database for the given controller instance. # Returns a session object or :none if no session is found. def self.get_session(controller) cookies = controller.send(:cookies) if cookies[:user_session] && session = self.find_session_by_token(cookies[:user_session]) session.temporary_token = cookies[:user_session] session.controller = controller session else :none end end # Find a session by a token (either from a hash or from the raw token) def self.find_session_by_token(token) return nil if token.blank? self.active.where("token = ? OR token_hash = ?", token, self.hash_token(token)).first end # Create a new session and return the newly created session object. # Any other sessions for the browser will be invalidated. def self.start(controller, params = {}) cookies = controller.send(:cookies) self.active.where(:browser_id => cookies[:browser_id]).each(&:invalidate!) user_object = params.delete(:user) session = self.new(params) if user_object session.user_type = user_object.class.to_s session.user_id = user_object.id end session.controller = controller session.browser_id = cookies[:browser_id] session.login_at = Time.now session.login_ip = controller.request.ip session.host = controller.request.host session.save! Authie.config.events.dispatch(:start_session, session) session end # Cleanup any old sessions. def self.cleanup Authie.config.events.dispatch(:before_cleanup) # Invalidate transient sessions that haven't been used self.active.where("expires_at IS NULL AND last_activity_at < ?", Authie.config.session_inactivity_timeout.ago).each(&:invalidate!) # Invalidate persistent sessions that have expired self.active.where("expires_at IS NOT NULL AND expires_at < ?", Time.now).each(&:invalidate!) Authie.config.events.dispatch(:after_cleanup) true end # Return a hash of a given token def self.hash_token(token) Digest::SHA256.hexdigest(token) end # Convert all existing active sessions to store their tokens in the database def self.convert_tokens_to_hashes active.where(:token_hash => nil).where("token is not null").each do |s| hash = self.hash_token(s.token) self.where(:id => s.id).update_all(:token_hash => hash, :token => nil) end end private # Return all cookies on the associated controller def cookies controller.send(:cookies) end end end add Session#user= to set the user polymorphically require 'secure_random_string' module Authie class Session < ActiveRecord::Base # Errors which will be raised when there's an issue with a session's # validity in the request. class ValidityError < Error; end class InactiveSession < ValidityError; end class ExpiredSession < ValidityError; end class BrowserMismatch < ValidityError; end class HostMismatch < ValidityError; end class NoParentSessionForRevert < Error; end # Set table name self.table_name = "authie_sessions" # Relationships parent_options = {:class_name => "Authie::Session"} parent_options[:optional] = true if ActiveRecord::VERSION::MAJOR >= 5 belongs_to :parent, parent_options # Scopes scope :active, -> { where(:active => true) } scope :asc, -> { order(:last_activity_at => :desc) } scope :for_user, -> (user) { where(:user_type => user.class.name, :user_id => user.id) } # Attributes serialize :data, Hash attr_accessor :controller attr_accessor :temporary_token before_validation do if self.user_agent.is_a?(String) self.user_agent = self.user_agent[0,255] end if self.last_activity_path.is_a?(String) self.last_activity_path = self.last_activity_path[0,255] end end before_create do self.temporary_token = SecureRandomString.new(44) self.token_hash = self.class.hash_token(self.temporary_token) if controller self.user_agent = controller.request.user_agent set_cookie! end end before_destroy do cookies.delete(:user_session) if controller end # Return the user that def user if self.user_id && self.user_type @user ||= self.user_type.constantize.find_by(:id => self.user_id) || :none @user == :none ? nil : @user end end # Set the user def user=(user) if user self.user_type = user.class.name self.user_id = user.id else self.user_type = nil self.user_id = nil end end # This method should be called each time a user performs an # action while authenticated with this session. def touch! self.check_security! self.last_activity_at = Time.now self.last_activity_ip = controller.request.ip self.last_activity_path = controller.request.path self.requests += 1 self.save! Authie.config.events.dispatch(:session_touched, self) true end # Sets the cookie on the associated controller. def set_cookie! cookies[:user_session] = { :value => self.temporary_token, :secure => controller.request.ssl?, :httponly => true, :expires => self.expires_at } Authie.config.events.dispatch(:session_cookie_updated, self) true end # Check the security of the session to ensure it can be used. def check_security! if controller if cookies[:browser_id] != self.browser_id invalidate! Authie.config.events.dispatch(:browser_id_mismatch_error, self) raise BrowserMismatch, "Browser ID mismatch" end unless self.active? invalidate! Authie.config.events.dispatch(:invalid_session_error, self) raise InactiveSession, "Session is no longer active" end if self.expired? invalidate! Authie.config.events.dispatch(:expired_session_error, self) raise ExpiredSession, "Persistent session has expired" end if self.inactive? invalidate! Authie.config.events.dispatch(:inactive_session_error, self) raise InactiveSession, "Non-persistent session has expired" end if self.host && self.host != controller.request.host invalidate! Authie.config.events.dispatch(:host_mismatch_error, self) raise HostMismatch, "Session was created on #{self.host} but accessed using #{controller.request.host}" end end end # Has this persistent session expired? def expired? self.expires_at && self.expires_at < Time.now end # Has a non-persistent session become inactive? def inactive? self.expires_at.nil? && self.last_activity_at && self.last_activity_at < Authie.config.session_inactivity_timeout.ago end # Allow this session to persist rather than expiring at the end of the # current browser session def persist! self.expires_at = Authie.config.persistent_session_length.from_now self.save! set_cookie! end # Is this a persistent session? def persistent? !!expires_at end # Activate an old session def activate! self.active = true self.save! end # Mark this session as invalid def invalidate! self.active = false self.save! if controller cookies.delete(:user_session) end Authie.config.events.dispatch(:session_invalidated, self) true end # Set some additional data in this session def set(key, value) self.data ||= {} self.data[key.to_s] = value self.save! end # Get some additional data from this session def get(key) (self.data ||= {})[key.to_s] end # Invalidate all sessions but this one for this user def invalidate_others! self.class.where("id != ?", self.id).for_user(self.user).each do |s| s.invalidate! end end # Note that we have just seen the user enter their password. def see_password! self.password_seen_at = Time.now self.save! Authie.config.events.dispatch(:seen_password, self) true end # Have we seen the user's password recently in this sesion? def recently_seen_password? !!(self.password_seen_at && self.password_seen_at >= Authie.config.sudo_session_timeout.ago) end # Is two factor authentication required for this request? def two_factored? !!(two_factored_at || self.parent_id) end # Mark this request as two factor authoritsed def mark_as_two_factored! self.two_factored_at = Time.now self.two_factored_ip = controller.request.ip self.save! Authie.config.events.dispatch(:marked_as_two_factored, self) true end # Create a new session for impersonating for the given user def impersonate!(user) self.class.start(controller, :user => user, :parent => self) end # Revert back to the parent session def revert_to_parent! if self.parent self.invalidate! self.parent.activate! self.parent.controller = self.controller self.parent.set_cookie! self.parent else raise NoParentSessionForRevert, "Session does not have a parent therefore cannot be reverted." end end # Is this the first session for this session's browser? def first_session_for_browser? self.class.where("id < ?", self.id).for_user(self.user).where(:browser_id => self.browser_id).empty? end # Is this the first session for the IP? def first_session_for_ip? self.class.where("id < ?", self.id).for_user(self.user).where(:login_ip => self.login_ip).empty? end # Find a session from the database for the given controller instance. # Returns a session object or :none if no session is found. def self.get_session(controller) cookies = controller.send(:cookies) if cookies[:user_session] && session = self.find_session_by_token(cookies[:user_session]) session.temporary_token = cookies[:user_session] session.controller = controller session else :none end end # Find a session by a token (either from a hash or from the raw token) def self.find_session_by_token(token) return nil if token.blank? self.active.where("token = ? OR token_hash = ?", token, self.hash_token(token)).first end # Create a new session and return the newly created session object. # Any other sessions for the browser will be invalidated. def self.start(controller, params = {}) cookies = controller.send(:cookies) self.active.where(:browser_id => cookies[:browser_id]).each(&:invalidate!) user_object = params.delete(:user) session = self.new(params) session.user = user_object session.controller = controller session.browser_id = cookies[:browser_id] session.login_at = Time.now session.login_ip = controller.request.ip session.host = controller.request.host session.save! Authie.config.events.dispatch(:start_session, session) session end # Cleanup any old sessions. def self.cleanup Authie.config.events.dispatch(:before_cleanup) # Invalidate transient sessions that haven't been used self.active.where("expires_at IS NULL AND last_activity_at < ?", Authie.config.session_inactivity_timeout.ago).each(&:invalidate!) # Invalidate persistent sessions that have expired self.active.where("expires_at IS NOT NULL AND expires_at < ?", Time.now).each(&:invalidate!) Authie.config.events.dispatch(:after_cleanup) true end # Return a hash of a given token def self.hash_token(token) Digest::SHA256.hexdigest(token) end # Convert all existing active sessions to store their tokens in the database def self.convert_tokens_to_hashes active.where(:token_hash => nil).where("token is not null").each do |s| hash = self.hash_token(s.token) self.where(:id => s.id).update_all(:token_hash => hash, :token => nil) end end private # Return all cookies on the associated controller def cookies controller.send(:cookies) end end end
require "authstrategies/version" require "warden" require "rack-flash" require "sinatra/base" require "active_record" require "authstrategies/session_serializer.rb" require "authstrategies/helpers.rb" require "authstrategues/password.rb" require "authstrategies/user.rb" require "authstrategies/middleware.rb" module Authstrategies module Base def self.registered(app) app.helpers Helpers app.use Warden::Manager do |manager| manager.failure_app = app manager.default_strategies :password end Warden::Strategies.add(:password, PasswordStrategy) app.get '/login/?' do redirect '/' if authenticated? erb :login end app.post '/login' do redirect '/' if authenticated? authenticate! if authenticated? flash[:notice] = "Logged in successfully!" redirect '/' else flash[:error] = env["warden"].message redirect '/login' end end app.get '/logout/?' do logout flash[:notice] = "Successfully logged out!" redirect '/' end app.post '/unauthenticated' do flash[:error] = "Invalid username or password!" redirect '/login' end app.get '/signup/?' do redirect '/' if authenticated? erb :signup end app.post '/signup' do redirect '/' if authenticated? user = User.new(params) if user.valid? user.save flash[:notice] = "Successfully signed up!" redirect '/' else flash[:error] = user.errors.messages redirect '/login' end end end end end fix typo require "authstrategies/version" require "warden" require "rack-flash" require "sinatra/base" require "active_record" require "authstrategies/session_serializer.rb" require "authstrategies/helpers.rb" require "authstrategies/password.rb" require "authstrategies/user.rb" require "authstrategies/middleware.rb" module Authstrategies module Base def self.registered(app) app.helpers Helpers app.use Warden::Manager do |manager| manager.failure_app = app manager.default_strategies :password end Warden::Strategies.add(:password, PasswordStrategy) app.get '/login/?' do redirect '/' if authenticated? erb :login end app.post '/login' do redirect '/' if authenticated? authenticate! if authenticated? flash[:notice] = "Logged in successfully!" redirect '/' else flash[:error] = env["warden"].message redirect '/login' end end app.get '/logout/?' do logout flash[:notice] = "Successfully logged out!" redirect '/' end app.post '/unauthenticated' do flash[:error] = "Invalid username or password!" redirect '/login' end app.get '/signup/?' do redirect '/' if authenticated? erb :signup end app.post '/signup' do redirect '/' if authenticated? user = User.new(params) if user.valid? user.save flash[:notice] = "Successfully signed up!" redirect '/' else flash[:error] = user.errors.messages redirect '/login' end end end end end
module AvaTax VERSION = '21.1.1'.freeze unless defined?(::AvaTax::VERSION) end pr82: update with master, bump to v21.1.2 module AvaTax VERSION = '21.1.2'.freeze unless defined?(::AvaTax::VERSION) end
module Awspec VERSION = '0.54.0' end Bump up version number module Awspec VERSION = '0.55.0' end
module Awspec VERSION = '0.79.2' end Bump up version number module Awspec VERSION = '0.80.0' end
# encoding: utf-8 module Backup class Version ## # Change the MAJOR, MINOR and PATCH constants below # to adjust the version of the Backup gem # # MAJOR: # Defines the major version # MINOR: # Defines the minor version # PATCH: # Defines the patch version MAJOR, MINOR, PATCH = 3, 0, 10 ## # Returns the major version ( big release based off of multiple minor releases ) def self.major MAJOR end ## # Returns the minor version ( small release based off of multiple patches ) def self.minor MINOR end ## # Returns the patch version ( updates, features and (crucial) bug fixes ) def self.patch PATCH end ## # Returns the current version of the Backup gem ( qualified for the gemspec ) def self.current "#{major}.#{minor}.#{patch}" end end end Releasing version 3.0.11! Fixes S3 absolute path issues. And the Archive method now uses the ' -f ' option to set the path to the generated archive file, rather than the > sign. This enables other versions of tar, such as the FreeBSD distro to make use of the Archive feature. # encoding: utf-8 module Backup class Version ## # Change the MAJOR, MINOR and PATCH constants below # to adjust the version of the Backup gem # # MAJOR: # Defines the major version # MINOR: # Defines the minor version # PATCH: # Defines the patch version MAJOR, MINOR, PATCH = 3, 0, 11 ## # Returns the major version ( big release based off of multiple minor releases ) def self.major MAJOR end ## # Returns the minor version ( small release based off of multiple patches ) def self.minor MINOR end ## # Returns the patch version ( updates, features and (crucial) bug fixes ) def self.patch PATCH end ## # Returns the current version of the Backup gem ( qualified for the gemspec ) def self.current "#{major}.#{minor}.#{patch}" end end end
# encoding: utf-8 module Backup VERSION = '4.1.1' end Release v4.1.2 # encoding: utf-8 module Backup VERSION = '4.1.2' end
module Bai2 class BaiFile private # ========================================================================= # Integrity verification # class IntegrityError < StandardError; end # Asserts integrity of a fully-parsed BaiFile by calculating checksums. # def assert_integrity! expectation = { sum: @trailer[:file_control_total], children: @trailer[:number_of_groups], records: @trailer[:number_of_records], } # Check children count unless expectation[:children] == (actual = self.groups.count) raise IntegrityError.new("Number of groups invalid: " \ + "expected #{expectation[:children]}, actually: #{actual}") end # Check sum vs. group sums actual_sum = self.groups.map do |group| group.instance_variable_get(:@trailer)[:group_control_total] end.reduce(0, &:+) unless expectation[:sum] == actual_sum raise IntegrityError.new( "Sums invalid: file: #{expectation[:sum]}, groups: #{actual_sum}") end # Run children assertions, which return number of records. May raise. records = self.groups.map {|g| g.send(:assert_integrity!) }.reduce(0, &:+) unless expectation[:records] == (actual = records + 2) raise IntegrityError.new( "Record count invalid: file: #{expectation[:records]}, groups: #{actual}") end end public class Group private # Asserts integrity of a fully-parsed BaiFile by calculating checksums. # def assert_integrity! expectation = { sum: @trailer[:group_control_total], children: @trailer[:number_of_accounts], records: @trailer[:number_of_records], } # Check children count unless expectation[:children] == (actual = self.accounts.count) raise IntegrityError.new("Number of accounts invalid: " \ + "expected #{expectation[:children]}, actually: #{actual}") end # Check sum vs. account sums actual_sum = self.accounts.map do |acct| acct.instance_variable_get(:@trailer)[:account_control_total] end.reduce(0, &:+) unless expectation[:sum] == actual_sum raise IntegrityError.new( "Sums invalid: file: #{expectation[:sum]}, groups: #{actual_sum}") end # Run children assertions, which return number of records. May raise. records = self.accounts.map {|a| a.send(:assert_integrity!) }.reduce(0, &:+) unless expectation[:records] == (actual = records + 2) raise IntegrityError.new( "Record count invalid: group: #{expectation[:records]}, accounts: #{actual}") end # Return record count records + 2 end end class Account private def assert_integrity! expectation = { sum: @trailer[:account_control_total], records: @trailer[:number_of_records], } # Check sum vs. summary + transaction sums actual_sum = self.transactions.map(&:amount).reduce(0, &:+) \ #+ self.summaries.map {|s| s[:amount] }.reduce(0, &:+) # TODO: ^ there seems to be a disconnect between what the spec defines # as the formula for the checksum and what SVB implements... unless expectation[:sum] == actual_sum raise IntegrityError.new( "Sums invalid: expected: #{expectation[:sum]}, actual: #{actual_sum}") end # Run children assertions, which return number of records. May raise. records = self.transactions.map do |tx| tx.instance_variable_get(:@record).physical_record_count end.reduce(0, &:+) unless expectation[:records] == (actual = records + 2) raise IntegrityError.new( "Record count invalid: file: #{expectation[:records]}, accounts: #{actual}") end # Return record count records + 2 end end end end style module Bai2 class BaiFile private # ========================================================================= # Integrity verification # class IntegrityError < StandardError; end # Asserts integrity of a fully-parsed BaiFile by calculating checksums. # def assert_integrity! expectation = { sum: @trailer[:file_control_total], children: @trailer[:number_of_groups], records: @trailer[:number_of_records], } # Check children count unless expectation[:children] == (actual = self.groups.count) raise IntegrityError.new("Number of groups invalid: " \ + "expected #{expectation[:children]}, actually: #{actual}") end # Check sum vs. group sums actual_sum = self.groups.map do |group| group.instance_variable_get(:@trailer)[:group_control_total] end.reduce(0, &:+) unless expectation[:sum] == actual_sum raise IntegrityError.new( "Sums invalid: file: #{expectation[:sum]}, groups: #{actual_sum}") end # Run children assertions, which return number of records. May raise. records = self.groups.map {|g| g.send(:assert_integrity!) }.reduce(0, &:+) unless expectation[:records] == (actual = records + 2) raise IntegrityError.new( "Record count invalid: file: #{expectation[:records]}, groups: #{actual}") end end public class Group private # Asserts integrity of a fully-parsed BaiFile by calculating checksums. # def assert_integrity! expectation = { sum: @trailer[:group_control_total], children: @trailer[:number_of_accounts], records: @trailer[:number_of_records], } # Check children count unless expectation[:children] == (actual = self.accounts.count) raise IntegrityError.new("Number of accounts invalid: " \ + "expected #{expectation[:children]}, actually: #{actual}") end # Check sum vs. account sums actual_sum = self.accounts.map do |acct| acct.instance_variable_get(:@trailer)[:account_control_total] end.reduce(0, &:+) unless expectation[:sum] == actual_sum raise IntegrityError.new( "Sums invalid: file: #{expectation[:sum]}, groups: #{actual_sum}") end # Run children assertions, which return number of records. May raise. records = self.accounts.map {|a| a.send(:assert_integrity!) }.reduce(0, &:+) unless expectation[:records] == (actual = records + 2) raise IntegrityError.new( "Record count invalid: group: #{expectation[:records]}, accounts: #{actual}") end # Return record count records + 2 end end class Account private def assert_integrity! expectation = { sum: @trailer[:account_control_total], records: @trailer[:number_of_records], } # Check sum vs. summary + transaction sums actual_sum = self.transactions.map(&:amount).reduce(0, &:+) \ #+ self.summaries.map {|s| s[:amount] }.reduce(0, &:+) # TODO: ^ there seems to be a disconnect between what the spec defines # as the formula for the checksum and what SVB implements... unless expectation[:sum] == actual_sum raise IntegrityError.new( "Sums invalid: expected: #{expectation[:sum]}, actual: #{actual_sum}") end # Run children assertions, which return number of records. May raise. records = self.transactions.map do |tx| tx.instance_variable_get(:@record).physical_record_count end.reduce(0, &:+) unless expectation[:records] == (actual = records + 2) raise IntegrityError.new("Record count invalid: " \ + "account: #{expectation[:records]}, transactions: #{actual}") end # Return record count records + 2 end end end end
require 'barthes/cache' module Barthes class Action def initialize(env) @env = env.dup client_class = Object.const_get(@env['client_class']) @client = client_class.new(env) end def indent(size, string) string.split("\n").map {|line| "\t" * size + "#{line}\n" } end def action(action) begin @env.update(action['env']) if action['env'] params = evaluate_params(action['params']) if action['expectations'] if action['max_loop'] action['max_loop'].to_i.times do sleep action['sleep'].to_i/1000 if action['sleep'] response = @client.action(params) action['expectations'].each do |expectation| result = @client.compare(response, evaluate_params(expectation)) expectation.update(result) end if action['expectations'].all? {|e| e['result'] == true } break end end end end sleep action['sleep'].to_i/1000 if action['sleep'] action['request'] = params action['response'] = response = @client.action(params) if action['expectations'] action['expectations'].each do |expectation| result = @client.compare(response, evaluate_params(expectation)) expectation.update(result) end if !action['expectations'].all? {|e| e['result'] == true } action['status'] = 'failure' end else action['status'] = 'success' end if cache_config = action['cache'] value = @client.extract(cache_config, response) action['cache']['value'] = value Barthes::Cache[cache_config['key']] = value end rescue StandardError => e action['status'] = 'error' action['error'] = { 'class' => e.class, 'message' => e.message, 'backtrace' => e.backtrace } end action end def evaluate_params(params) new_params = {} params.each do |k, v| if v.class == String new_v = v.gsub(/\$\{(.+?)\}/) { @env[$1] } new_v = new_v.gsub(/\@\{(.+?)\}/) { Barthes::Cache[$1] } else new_v = v end new_params[k] = new_v end new_params end end end update action require 'barthes/cache' module Barthes class Action def initialize(env) @env = env.dup client_class = Object.const_get(@env['client_class']) @client = client_class.new(env) end def indent(size, string) string.split("\n").map {|line| "\t" * size + "#{line}\n" } end def action(action) begin @env.update(action['env']) if action['env'] params = evaluate_params(action['params']) if action['expectations'] if action['max_loop'] action['max_loop'].to_i.times do sleep action['sleep'].to_i/1000 if action['sleep'] response = @client.action(params) action['expectations'].each do |expectation| result = @client.compare(response, evaluate_params(expectation)) expectation.update(result) end if action['expectations'].all? {|e| e['result'] == true } break end end end end sleep action['sleep'].to_i/1000 if action['sleep'] action['request'] = params action['response'] = response = @client.action(params) if action['expectations'] && !action['expectations'].empty? action['expectations'].each do |expectation| result = @client.compare(response, evaluate_params(expectation)) expectation.update(result) end if !action['expectations'].all? {|e| e['result'] == true } action['status'] = 'failure' else action['status'] = 'success' end else action['status'] = 'success' end if cache_config = action['cache'] value = @client.extract(cache_config, response) action['cache']['value'] = value Barthes::Cache[cache_config['key']] = value end rescue StandardError => e action['status'] = 'error' action['error'] = { 'class' => e.class, 'message' => e.message, 'backtrace' => e.backtrace } end action end def evaluate_params(params) new_params = {} params.each do |k, v| if v.class == String new_v = v.gsub(/\$\{(.+?)\}/) { @env[$1] } new_v = new_v.gsub(/\@\{(.+?)\}/) { Barthes::Cache[$1] } else new_v = v end new_params[k] = new_v end new_params end end end
# -*- encoding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 # baruwa: Ruby bindings for the Baruwa REST API # Copyright (C) 2015 Andrew Colin Kissa <andrew@topdog.za.net> # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. module Baruwa VERSION = "0.0.1" end * Bumped version # -*- encoding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 # baruwa: Ruby bindings for the Baruwa REST API # Copyright (C) 2015 Andrew Colin Kissa <andrew@topdog.za.net> # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. module Baruwa VERSION = "0.0.2" end
module Beetle class Message FORMAT_VERSION = 1 FLAG_REDUNDANT = 2 DEFAULT_TTL = 1.day DEFAULT_HANDLER_TIMEOUT = 300.seconds DEFAULT_HANDLER_EXECUTION_ATTEMPTS = 5 DEFAULT_HANDLER_EXECUTION_ATTEMPTS_DELAY = 10.seconds DEFAULT_EXCEPTION_LIMIT = 1 attr_reader :server, :queue, :header, :body, :uuid, :data, :format_version, :flags, :expires_at attr_reader :timeout, :delay, :attempts_limit, :exceptions_limit def initialize(queue, header, body, opts = {}) @queue = queue @header = header @body = body setup(opts) decode end def setup(opts) @server = opts[:server] @timeout = opts[:timeout] || DEFAULT_HANDLER_TIMEOUT @attempts_limit = opts[:attempts] || DEFAULT_HANDLER_EXECUTION_ATTEMPTS @delay = opts[:delay] || DEFAULT_HANDLER_EXECUTION_ATTEMPTS_DELAY @exceptions_limit = opts[:exceptions] || DEFAULT_EXCEPTION_LIMIT end def decode @format_version, @flags, @expires_at, @uuid, @data = @body.unpack("nnNA36A*") end def self.encode(data, opts = {}) expires_at = ttl_to_expiration_time(opts[:ttl] || DEFAULT_TTL) flags = 0 flags |= FLAG_REDUNDANT if opts[:redundant] [FORMAT_VERSION, flags, expires_at, generate_uuid.to_s, data.to_s].pack("nnNA36A*") end def msg_id @msg_id ||= "msgid:#{queue}:#{uuid}" end def now Time.now.to_i end def expired?(expiration_time = Time.now.to_i) @expires_at < expiration_time end def self.ttl_to_expiration_time(ttl) Time.now.to_i + ttl.to_i end def self.generate_uuid UUID4R::uuid(1) end def redundant? @flags & FLAG_REDUNDANT == FLAG_REDUNDANT end def set_timeout! redis.set(timeout_key, now + timeout) end def timed_out? (t = redis.get(timeout_key)) && t.to_i < now end def timed_out! redis.set(timeout_key, 0) end def completed? redis.get(status_key) == "completed" end def completed! redis.set(status_key, "completed") timed_out! end def delayed? (t = redis.get(delay_key)) && t.to_i > now end def set_delay! redis.set(delay_key, now + delay) end def increment_execution_attempts! redis.incr(execution_attempts_key) end def attempts_limit_reached? (limit = redis.get(execution_attempts_key)) && limit.to_i >= attempts_limit end def increment_exception_count! redis.incr(exceptions_key) end def exceptions_limit_reached? (limit = redis.get(exceptions_key)) && limit.to_i >= exceptions_limit end def key_exists? new_message = redis.setnx(status_key, "incomplete") unless new_message logger.debug "received duplicate message: #{status_key} on queue: #{@queue}" end !new_message end def aquire_mutex! if mutex = redis.setnx(mutex_key, now) logger.debug "aquired mutex: #{msg_id}" else redis.del(mutex_key) logger.debug "deleted mutex: #{msg_id}" end mutex end def self.redis @redis ||= Redis.new end def self.redis=redis @redis = redis end def process(block) logger.debug "Processing message #{msg_id}" begin process_internal(block) rescue Exception => e logger.warn "Exception '#{e}' during invocation of message handler for #{msg_id}" logger.warn "Backtrace: #{e.backtrace.join("\n")}" raise end end def status_key keys[:status] ||= "#{msg_id}:status" end def ack_count_key keys[:ack_count] ||= "#{msg_id}:ack_count" end def timeout_key keys[:timeout] ||= "#{msg_id}:timeout" end def delay_key keys[:delay] ||= "#{msg_id}:delay" end def execution_attempts_key keys[:attempts] ||= "#{msg_id}:attempts" end def mutex_key keys[:mutex] ||= "#{msg_id}:mutex" end def exceptions_key keys[:exceptions] ||= "#{msg_id}:exceptions" end def all_keys [status_key, ack_count_key, timeout_key, delay_key, execution_attempts_key, exceptions_key, mutex_key] end def keys @keys ||= {} end private def process_internal(block) if expired? logger.warn "Ignored expired message (#{msg_id})!" ack! return end if !key_exists? set_timeout! run_handler!(block) elsif completed? ack! elsif delayed? logger.warn "Ignored delayed message (#{msg_id})!" elsif !timed_out? raise HandlerNotYetTimedOut elsif attempts_limit_reached? ack! raise AttemptsLimitReached, "Reached the handler execution attempts limit: #{attempts_limit} on #{msg_id}" elsif exceptions_limit_reached? ack! raise ExceptionsLimitReached, "Reached the handler exceptions limit: #{exceptions_limit} on #{msg_id}" else set_timeout! run_handler!(block) if aquire_mutex! end end def run_handler!(block) begin increment_execution_attempts! block.call(self) rescue Exception => e increment_exception_count! if attempts_limit_reached? ack! raise AttemptsLimitReached, "Reached the handler execution attempts limit: #{attempts_limit} on #{msg_id}" elsif exceptions_limit_reached? ack! raise ExceptionsLimitReached, "Reached the handler exceptions limit: #{exceptions_limit} on #{msg_id}" else timed_out! set_delay! raise HandlerCrash.new(e) end end completed! ack! end def redis self.class.redis end def logger self.class.logger end def self.logger Beetle.config.logger end def ack! logger.debug "ack! for message #{msg_id}" header.ack if !redundant? || redis.incr(ack_count_key) == 2 redis.del(all_keys) end end end end changed the redundant flag value module Beetle class Message FORMAT_VERSION = 1 FLAG_REDUNDANT = 1 DEFAULT_TTL = 1.day DEFAULT_HANDLER_TIMEOUT = 300.seconds DEFAULT_HANDLER_EXECUTION_ATTEMPTS = 5 DEFAULT_HANDLER_EXECUTION_ATTEMPTS_DELAY = 10.seconds DEFAULT_EXCEPTION_LIMIT = 1 attr_reader :server, :queue, :header, :body, :uuid, :data, :format_version, :flags, :expires_at attr_reader :timeout, :delay, :attempts_limit, :exceptions_limit def initialize(queue, header, body, opts = {}) @queue = queue @header = header @body = body setup(opts) decode end def setup(opts) @server = opts[:server] @timeout = opts[:timeout] || DEFAULT_HANDLER_TIMEOUT @attempts_limit = opts[:attempts] || DEFAULT_HANDLER_EXECUTION_ATTEMPTS @delay = opts[:delay] || DEFAULT_HANDLER_EXECUTION_ATTEMPTS_DELAY @exceptions_limit = opts[:exceptions] || DEFAULT_EXCEPTION_LIMIT end def decode @format_version, @flags, @expires_at, @uuid, @data = @body.unpack("nnNA36A*") end def self.encode(data, opts = {}) expires_at = ttl_to_expiration_time(opts[:ttl] || DEFAULT_TTL) flags = 0 flags |= FLAG_REDUNDANT if opts[:redundant] [FORMAT_VERSION, flags, expires_at, generate_uuid.to_s, data.to_s].pack("nnNA36A*") end def msg_id @msg_id ||= "msgid:#{queue}:#{uuid}" end def now Time.now.to_i end def expired?(expiration_time = Time.now.to_i) @expires_at < expiration_time end def self.ttl_to_expiration_time(ttl) Time.now.to_i + ttl.to_i end def self.generate_uuid UUID4R::uuid(1) end def redundant? @flags & FLAG_REDUNDANT == FLAG_REDUNDANT end def set_timeout! redis.set(timeout_key, now + timeout) end def timed_out? (t = redis.get(timeout_key)) && t.to_i < now end def timed_out! redis.set(timeout_key, 0) end def completed? redis.get(status_key) == "completed" end def completed! redis.set(status_key, "completed") timed_out! end def delayed? (t = redis.get(delay_key)) && t.to_i > now end def set_delay! redis.set(delay_key, now + delay) end def increment_execution_attempts! redis.incr(execution_attempts_key) end def attempts_limit_reached? (limit = redis.get(execution_attempts_key)) && limit.to_i >= attempts_limit end def increment_exception_count! redis.incr(exceptions_key) end def exceptions_limit_reached? (limit = redis.get(exceptions_key)) && limit.to_i >= exceptions_limit end def key_exists? new_message = redis.setnx(status_key, "incomplete") unless new_message logger.debug "received duplicate message: #{status_key} on queue: #{@queue}" end !new_message end def aquire_mutex! if mutex = redis.setnx(mutex_key, now) logger.debug "aquired mutex: #{msg_id}" else redis.del(mutex_key) logger.debug "deleted mutex: #{msg_id}" end mutex end def self.redis @redis ||= Redis.new end def self.redis=redis @redis = redis end def process(block) logger.debug "Processing message #{msg_id}" begin process_internal(block) rescue Exception => e logger.warn "Exception '#{e}' during invocation of message handler for #{msg_id}" logger.warn "Backtrace: #{e.backtrace.join("\n")}" raise end end def status_key keys[:status] ||= "#{msg_id}:status" end def ack_count_key keys[:ack_count] ||= "#{msg_id}:ack_count" end def timeout_key keys[:timeout] ||= "#{msg_id}:timeout" end def delay_key keys[:delay] ||= "#{msg_id}:delay" end def execution_attempts_key keys[:attempts] ||= "#{msg_id}:attempts" end def mutex_key keys[:mutex] ||= "#{msg_id}:mutex" end def exceptions_key keys[:exceptions] ||= "#{msg_id}:exceptions" end def all_keys [status_key, ack_count_key, timeout_key, delay_key, execution_attempts_key, exceptions_key, mutex_key] end def keys @keys ||= {} end private def process_internal(block) if expired? logger.warn "Ignored expired message (#{msg_id})!" ack! return end if !key_exists? set_timeout! run_handler!(block) elsif completed? ack! elsif delayed? logger.warn "Ignored delayed message (#{msg_id})!" elsif !timed_out? raise HandlerNotYetTimedOut elsif attempts_limit_reached? ack! raise AttemptsLimitReached, "Reached the handler execution attempts limit: #{attempts_limit} on #{msg_id}" elsif exceptions_limit_reached? ack! raise ExceptionsLimitReached, "Reached the handler exceptions limit: #{exceptions_limit} on #{msg_id}" else set_timeout! run_handler!(block) if aquire_mutex! end end def run_handler!(block) begin increment_execution_attempts! block.call(self) rescue Exception => e increment_exception_count! if attempts_limit_reached? ack! raise AttemptsLimitReached, "Reached the handler execution attempts limit: #{attempts_limit} on #{msg_id}" elsif exceptions_limit_reached? ack! raise ExceptionsLimitReached, "Reached the handler exceptions limit: #{exceptions_limit} on #{msg_id}" else timed_out! set_delay! raise HandlerCrash.new(e) end end completed! ack! end def redis self.class.redis end def logger self.class.logger end def self.logger Beetle.config.logger end def ack! logger.debug "ack! for message #{msg_id}" header.ack if !redundant? || redis.incr(ack_count_key) == 2 redis.del(all_keys) end end end end
require Pathname('rexml/document') begin require 'faster_csv' rescue LoadError nil end begin require Pathname('json/ext') rescue LoadError require Pathname('json/pure') end module DataMapper module Serialize # Serialize a Resource to JavaScript Object Notation (JSON; RFC 4627) # # @return <String> a JSON representation of the Resource def to_json(options = {}) result = '{ ' fields = [] propset = properties_to_serialize(options) fields += propset.map do |property| "#{property.name.to_json}: #{send(property.getter).to_json}" end if self.respond_to?(:serialize_properties) self.serialize_properties.each do |k,v| fields << "#{k.to_json}: #{v.to_json}" end end if self.class.respond_to?(:read_only_attributes) && exclude_read_only self.class.read_only_attributes.each do |property| fields << "#{property.to_json}: #{send(property).to_json}" end end # add methods (options[:methods] || []).each do |meth| if self.respond_to?(meth) fields << "#{meth.to_json}: #{send(meth).to_json}" end end # Note: if you want to include a whole other model via relation, use :methods # comments.to_json(:relationships=>{:user=>{:include=>[:first_name],:methods=>[:age]}}) # add relationships (options[:relationships] || {}).each do |rel,opts| if self.respond_to?(rel) fields << "#{rel.to_json}: #{send(rel).to_json(opts)}" end end result << fields.join(', ') result << ' }' result end # Serialize a Resource to comma-separated values (CSV). # # @return <String> a CSV representation of the Resource def to_csv(writer = '') FasterCSV.generate(writer) do |csv| row = [] self.class.properties(repository.name).each do |property| row << send(property.name).to_s end csv << row end end # Serialize a Resource to XML # # @return <REXML::Document> an XML representation of this Resource def to_xml(opts = {}) to_xml_document(opts).to_s end # Serialize a Resource to YAML # # @return <YAML> a YAML representation of this Resource def to_yaml(opts = {}) YAML::quick_emit(object_id,opts) do |out| out.map(nil,to_yaml_style) do |map| propset = properties_to_serialize(opts) propset.each do |property| value = send(property.name.to_sym) map.add(property.name, value.is_a?(Class) ? value.to_s : value) end (instance_variable_get("@yaml_addes") || []).each do |k,v| map.add(k.to_s,v) end end end end protected # Returns propreties to serialize based on :only or :exclude arrays, if provided # :only takes precendence over :exclude # # @return <Array> properties that need to be serialized def properties_to_serialize(options) only_properties = Array(options[:only]) excluded_properties = Array(options[:exclude]) exclude_read_only = options[:without_read_only_attributes] || false self.class.properties(repository.name).reject do |p| if only_properties.include? p.name false else excluded_properties.include?(p.name) || !(only_properties.empty? || only_properties.include?(p.name)) end end end # Return the name of this Resource - to be used as the root element name. # This can be overloaded. # # @return <String> name of this Resource def xml_element_name Extlib::Inflection.underscore(self.class.name) end # Return a REXML::Document representing this Resource # # @return <REXML::Document> an XML representation of this Resource def to_xml_document(opts={}, doc=nil) doc ||= REXML::Document.new root = doc.add_element(xml_element_name) #TODO old code base was converting single quote to double quote on attribs propset = properties_to_serialize(opts) propset.each do |property| value = send(property.name) node = root.add_element(property.name.to_s) unless property.type == String node.attributes["type"] = property.type.to_s.downcase end node << REXML::Text.new(value.to_s) unless value.nil? end # add methods (opts[:methods] || []).each do |meth| if self.respond_to?(meth) xml_name = meth.to_s.gsub(/[^a-z0-9_]/, '') node = root.add_element(xml_name) value = send(meth) node << REXML::Text.new(value.to_s, :raw => true) unless value.nil? end end doc end end # module Serialize module Resource include Serialize end # module Resource class Collection def to_yaml(opts = {}) # FIXME: Don't double handle the YAML (remove the YAML.load) to_a.collect {|x| YAML.load(x.to_yaml(opts)) }.to_yaml end def to_json(opts = {}) "[" << map {|e| e.to_json(opts)}.join(",") << "]" end def to_xml(opts = {}) to_xml_document(opts).to_s end def to_csv result = "" each do |item| result << item.to_csv + "\n" end result end protected def xml_element_name Extlib::Inflection.tableize(self.model.to_s) end def to_xml_document(opts={}) doc = REXML::Document.new root = doc.add_element(xml_element_name) root.attributes["type"] = 'array' each do |item| item.send(:to_xml_document, opts, root) end doc end end end # module DataMapper Add :methods to #to_yaml require Pathname('rexml/document') begin require 'faster_csv' rescue LoadError nil end begin require Pathname('json/ext') rescue LoadError require Pathname('json/pure') end module DataMapper module Serialize # Serialize a Resource to JavaScript Object Notation (JSON; RFC 4627) # # @return <String> a JSON representation of the Resource def to_json(options = {}) result = '{ ' fields = [] propset = properties_to_serialize(options) fields += propset.map do |property| "#{property.name.to_json}: #{send(property.getter).to_json}" end if self.respond_to?(:serialize_properties) self.serialize_properties.each do |k,v| fields << "#{k.to_json}: #{v.to_json}" end end if self.class.respond_to?(:read_only_attributes) && exclude_read_only self.class.read_only_attributes.each do |property| fields << "#{property.to_json}: #{send(property).to_json}" end end # add methods (options[:methods] || []).each do |meth| if self.respond_to?(meth) fields << "#{meth.to_json}: #{send(meth).to_json}" end end # Note: if you want to include a whole other model via relation, use :methods # comments.to_json(:relationships=>{:user=>{:include=>[:first_name],:methods=>[:age]}}) # add relationships (options[:relationships] || {}).each do |rel,opts| if self.respond_to?(rel) fields << "#{rel.to_json}: #{send(rel).to_json(opts)}" end end result << fields.join(', ') result << ' }' result end # Serialize a Resource to comma-separated values (CSV). # # @return <String> a CSV representation of the Resource def to_csv(writer = '') FasterCSV.generate(writer) do |csv| row = [] self.class.properties(repository.name).each do |property| row << send(property.name).to_s end csv << row end end # Serialize a Resource to XML # # @return <REXML::Document> an XML representation of this Resource def to_xml(opts = {}) to_xml_document(opts).to_s end # Serialize a Resource to YAML # # @return <YAML> a YAML representation of this Resource def to_yaml(opts = {}) YAML::quick_emit(object_id,opts) do |out| out.map(nil,to_yaml_style) do |map| propset = properties_to_serialize(opts) propset.each do |property| value = send(property.name.to_sym) map.add(property.name, value.is_a?(Class) ? value.to_s : value) end # add methods (opts[:methods] || []).each do |meth| if self.respond_to?(meth) map.add(meth.to_sym, send(meth)) end end (instance_variable_get("@yaml_addes") || []).each do |k,v| map.add(k.to_s,v) end end end end protected # Returns propreties to serialize based on :only or :exclude arrays, if provided # :only takes precendence over :exclude # # @return <Array> properties that need to be serialized def properties_to_serialize(options) only_properties = Array(options[:only]) excluded_properties = Array(options[:exclude]) exclude_read_only = options[:without_read_only_attributes] || false self.class.properties(repository.name).reject do |p| if only_properties.include? p.name false else excluded_properties.include?(p.name) || !(only_properties.empty? || only_properties.include?(p.name)) end end end # Return the name of this Resource - to be used as the root element name. # This can be overloaded. # # @return <String> name of this Resource def xml_element_name Extlib::Inflection.underscore(self.class.name) end # Return a REXML::Document representing this Resource # # @return <REXML::Document> an XML representation of this Resource def to_xml_document(opts={}, doc=nil) doc ||= REXML::Document.new root = doc.add_element(xml_element_name) #TODO old code base was converting single quote to double quote on attribs propset = properties_to_serialize(opts) propset.each do |property| value = send(property.name) node = root.add_element(property.name.to_s) unless property.type == String node.attributes["type"] = property.type.to_s.downcase end node << REXML::Text.new(value.to_s) unless value.nil? end # add methods (opts[:methods] || []).each do |meth| if self.respond_to?(meth) xml_name = meth.to_s.gsub(/[^a-z0-9_]/, '') node = root.add_element(xml_name) value = send(meth) node << REXML::Text.new(value.to_s, :raw => true) unless value.nil? end end doc end end # module Serialize module Resource include Serialize end # module Resource class Collection def to_yaml(opts = {}) # FIXME: Don't double handle the YAML (remove the YAML.load) to_a.collect {|x| YAML.load(x.to_yaml(opts)) }.to_yaml end def to_json(opts = {}) "[" << map {|e| e.to_json(opts)}.join(",") << "]" end def to_xml(opts = {}) to_xml_document(opts).to_s end def to_csv result = "" each do |item| result << item.to_csv + "\n" end result end protected def xml_element_name Extlib::Inflection.tableize(self.model.to_s) end def to_xml_document(opts={}) doc = REXML::Document.new root = doc.add_element(xml_element_name) root.attributes["type"] = 'array' each do |item| item.send(:to_xml_document, opts, root) end doc end end end # module DataMapper
module Beetle VERSION = "0.3.0.rc.11" end Version bump [ci skip] module Beetle VERSION = "0.3.0.rc.12" end
module BEncode class << self # BEncodes +obj+ def dump(obj) obj.bencode end # Bdecodes +str+ def load(str) require 'strscan' scanner = StringScanner.new(str) obj = parse(scanner) raise BEncode::DecodeError unless scanner.eos? return obj end # Bdecodes the file located at +path+ def load_file(path) load(File.open(path).read) end def parse(scanner) # :nodoc: case scanner.scan(/[ild]|\d+:/) when "i" number = scanner.scan(/0|(?:-?[1-9][0-9]*)/) raise BEncode::DecodeError unless number and scanner.scan(/e/) return number.to_i when "l" ary = [] # TODO: There must be a smarter way of doing this... ary.push(parse(scanner)) until scanner.peek(1) == "e" scanner.pos += 1 return ary when "d" hsh = {} until scanner.peek(1) == "e" key, value = parse(scanner), parse(scanner) unless key.is_a? String raise BEncode::DecodeError, "key must be a string" end hsh.store(key, value) end scanner.pos += 1 return hsh when /\d+:/ length = Integer($~.string.chop) str = scanner.peek(length) begin scanner.pos += length rescue RangeError raise BEncode::DecodeError, "invalid string length" end return str else raise BEncode::DecodeError end end private :parse end end class String # # Bdecodes the String object and returns the data serialized # through bencoding. # # "li1ei2ei3ee".bdecode #=> [1, 2, 3] # def bdecode BEncode.load(self) end end Patched load_file to work properly under Windows module BEncode class << self # BEncodes +obj+ def dump(obj) obj.bencode end # Bdecodes +str+ def load(str) require 'strscan' scanner = StringScanner.new(str) obj = parse(scanner) raise BEncode::DecodeError unless scanner.eos? return obj end # Bdecodes the file located at +path+ def load_file(path) if RUBY_PLATFORM =~ /(win|w)32$/ load(File.open(path, 'rb').read) else load(File.open(path).read) end end def parse(scanner) # :nodoc: case scanner.scan(/[ild]|\d+:/) when "i" number = scanner.scan(/0|(?:-?[1-9][0-9]*)/) raise BEncode::DecodeError unless number and scanner.scan(/e/) return number.to_i when "l" ary = [] # TODO: There must be a smarter way of doing this... ary.push(parse(scanner)) until scanner.peek(1) == "e" scanner.pos += 1 return ary when "d" hsh = {} until scanner.peek(1) == "e" key, value = parse(scanner), parse(scanner) unless key.is_a? String raise BEncode::DecodeError, "key must be a string" end hsh.store(key, value) end scanner.pos += 1 return hsh when /\d+:/ length = Integer($~.string.chop) str = scanner.peek(length) begin scanner.pos += length rescue RangeError raise BEncode::DecodeError, "invalid string length" end return str else raise BEncode::DecodeError end end private :parse end end class String # # Bdecodes the String object and returns the data serialized # through bencoding. # # "li1ei2ei3ee".bdecode #=> [1, 2, 3] # def bdecode BEncode.load(self) end end
module Biaoti VERSION = "0.1.0" end Bump version to 0.1.1 module Biaoti VERSION = "0.1.1" end
# Native Ruby Float extemsions # Here we add some of the methods available in BinFloat to Float. # # The set of constants with Float metadata is also augmented. # The built-in contantas are: # Note that this uses the "fractional significand" interpretation, # i.e. the significand has the radix point before its first digit. # # Float::RADIX : b = Radix of exponent representation,2 # # Float::MANT_DIG : p = bits (base-RADIX digits) in the significand # # Float::DIG : q = Number of decimal digits such that any floating-point number with q # decimal digits can be rounded into a floating-point number with p radix b # digits and back again without change to the q decimal digits, # q = p * log10(b) if b is a power of 10 # q = floor((p - 1) * log10(b)) otherwise # ((Float::MANT_DIG-1)*Math.log(FLoat::RADIX)/Math.log(10)).floor # # Float::MIN_EXP : emin = Minimum int x such that Float::RADIX**(x-1) is a normalized float # # Float::MIN_10_EXP : Minimum negative integer such that 10 raised to that power is in the # range of normalized floating-point numbers, # ceil(log10(b) * (emin - 1)) # # Float::MAX_EXP : emax = Maximum int x such that Float::RADIX**(x-1) is a representable float # # Float::MAX_10_EXP : Maximum integer such that 10 raised to that power is in the range of # representable finite floating-point numbers, # floor(log10((1 - b**-p) * b**emax)) # # Float::MAX : Maximum representable finite floating-point number # (1 - b**-p) * b**emax # # Float::EPSILON : The difference between 1 and the least value greater than 1 that is # representable in the given floating point type # b**(1-p) # Math.ldexp(*Math.frexp(1).collect{|e| e.kind_of?(Integer) ? e-(Float::MANT_DIG-1) : e}) # # Float::MIN : Minimum normalized positive floating-point number # b**(emin - 1). # # Float::ROUNDS : Addition rounds to 0: zero, 1: nearest, 2: +inf, 3: -inf, -1: unknown. # # Additional contants defined here: # # Float::DECIMAL_DIG : Number of decimal digits, n, such that any floating-point number can be rounded # to a floating-point number with n decimal digits and back again without # change to the value, # pmax * log10(b) if b is a power of 10 # ceil(1 + pmax * log10(b)) otherwise # DECIMAL_DIG = (MANT_DIG*Math.log(RADIX)/Math.log(10)).ceil+1 # # Float::MIN_N : Minimum normalized number == MAX_D.next == MIN # # Float::MAX_D : Maximum denormal number == MIN_N.prev # # Float::MIN_D : Minimum non zero positive denormal number == 0.0.next # # Float::MAX_F : Maximum significand # class Float DECIMAL_DIG = (MANT_DIG*Math.log(RADIX)/Math.log(10)).ceil+1 # Compute the adjacent floating point values: largest value not larger than # this and smallest not smaller. def neighbours f,e = Math.frexp(self) e = Float::MIN_EXP if f==0 e = [Float::MIN_EXP,e].max dx = Math.ldexp(1,e-Float::MANT_DIG) #Math.ldexp(Math.ldexp(1.0,-Float::MANT_DIG),e) min_f = 0.5 #0.5==Math.ldexp(2**(bits-1),-Float::MANT_DIG) max_f = 1.0 - Math.ldexp(1,-Float::MANT_DIG) if f==max_f high = self + dx*2 elsif f==-min_f && e!=Float::MIN_EXP high = self + dx/2 else high = self + dx end if e==Float::MIN_EXP || f!=min_f low = self - dx elsif f==-max_f high = self - dx*2 else low = self - dx/2 end [low, high] end # Previous floating point value def prev neighbours[0] end # Next floating point value; e.g. 1.0.next == 1.0+Float::EPSILON def next neighbours[1] end # Synonym of next, named in the style of Decimal (GDA) def next_plus self.next end # Synonym of prev, named in the style of Decimal (GDA) def next_minus self.prev end def next_toward(other) comparison = self <=> other return self.copy_sign(other) if comparison == 0 if comparison == -1 result = self.next_plus(context) else # comparison == 1 result = self.next_minus(context) end end # Sign: -1 for minus, +1 for plus, nil for nan (note that Float zero is signed) def sign if nan? nil elsif self==0 self.to_s[0,1] == "-" ? -1 : +1 else self < 0 ? -1 : +1 end end # Return copy of self with the sign of other def copy_sign(other) self_sign = self.sign other_sign = other.sign if self_sign && other_sign if self_sign == other_sign self else -self end else nan end end # Returns the internal representation of the number, composed of: # * a sign which is +1 for plus and -1 for minus # * a coefficient (significand) which is a nonnegative integer # * an exponent (an integer) or :inf, :nan or :snan for special values # The value of non-special numbers is sign*coefficient*10^exponent def split sign = self.sign if nan? exp = :nan elsif infinite? exp = :inf else coeff,exp = Math.frexp(self) coeff = Math.ldexp(coeff,Float::MANT_DIG).to_i exp -= Float::MANT_DIG end [sign, coeff, exp] end def int_exp end # Return the value of the number as an signed integer and a scale. def to_int_scale if special? nil else coeff,exp = Math.frexp(x) coeff = Math.ldexp(coeff,Float::MANT_DIG).to_i, exp -= Float::MANT_DIG [coeff, exp] end end # Minimum normalized number == MAX_D.next MIN_N = Math.ldexp(0.5,Float::MIN_EXP) # == nxt(MAX_D) == Float::MIN # Maximum denormal number == MIN_N.prev MAX_D = Math.ldexp(Math.ldexp(1,Float::MANT_DIG-1)-1,Float::MIN_EXP-Float::MANT_DIG) # Minimum non zero positive denormal number == 0.0.next MIN_D = Math.ldexp(1,Float::MIN_EXP-Float::MANT_DIG); # Maximum significand == Math.ldexp(Math.ldexp(1,Float::MANT_DIG)-1,-Float::MANT_DIG) MAX_F = Math.frexp(Float::MAX)[0] == Math.ldexp(Math.ldexp(1,Float::MANT_DIG)-1,-Float::MANT_DIG) # ulp (unit in the last place) according to the definition proposed by J.M. Muller in # "On the definition of ulp(x)" INRIA No. 5504 def ulp(mode=:low) return self if nan? x = abs if x < Math.ldexp(1,MIN_EXP) # x < RADIX*MIN_N Math.ldexp(1,MIN_EXP-MANT_DIG) # res = MIN_D elsif x > MAX # x > Math.ldexp(1-Math.ldexp(1,-MANT_DIG),MAX_EXP) Math.ldexp(1,MAX_EXP-MANT_DIG) # res = MAX - MAX.prev else f,e = Math.frexp(x) e -= 1 if f==Math.ldexp(1,-1) if mode==:low # assign the smaller ulp to radix powers Math.ldexp(1,e-MANT_DIG) end end def special? nan? || infinite? end def zero? self == 0.0 end def normal? if special? || zero? false else self.abs >= MIN_N end end def subnormal? if special? || zero? false else self.abs < MIN_N end end class <<self def radix Float::RADIX end # NaN (not a number value) def nan 0.0/0.0 end # zero value with specified sign def zero(sign=+1) (sign < 0) ? -0.0 : 0.0 end # infinitie value with specified sign def infinite(sign=+1) (sign < 0) ? -1.0/0.0 : 1.0/0.0 end # This provides an common interface (with BigFloat classes) to precision, rounding, etc. def context self end # This is the difference between 1.0 and the smallest floating-point # value greater than 1.0, radix_power(1-significand_precision) # # We have: # Float.epsilon == (1.0.next-1.0) def epsilon(sign=+1) (sign < 0) ? -EPSILON : EPSILON end # The strict epsilon is the smallest value that produces something different from 1.0 # wehen added to 1.0. It may be smaller than the general epsilon, because # of the particular rounding rules used with the floating point format. # This is only meaningful when well-defined rules are used for rounding the result # of floating-point addition. # # We have: # (Float.strict_epsilon+1.0) == 1.0.next # (Float.strict_epsilon.prev+1.0) == 1.0 def strict_epsilon(sign=+1, round=nil) # We don't rely on Float::ROUNDS eps = minimum_nonzero if (1.0+eps) > 1.0 eps else f,e = Math.frexp(1) eps = Math.ldexp(f.next,e-MANT_DIG) if (1.0+eps) > 1.0 eps else eps = Math.ldexp(f,e-MANT_DIG) if (1.0+eps) > 1.0 eps else puts "here" puts "f=#{f} e=#{e} exp=#{e-MANT_DIG} => #{Math.ldexp(f,e-MANT_DIG)} eps = #{epsilon}" Math.ldexp(f,e-MANT_DIG+1) end end end end # This is the maximum relative error corresponding to 1/2 ulp: # (radix/2)*radix_power(-significand_precision) == epsilon/2 # This is called "machine epsilon" in [Goldberg] # We have: # # Float.half_epsilon == 0.5*Float.epsilon def half_epsilon(sign=+1) # 0.5*epsilon(sign) f,e = Math.frexp(1) Math.ldexp(f, e-MANT_DIG) end # minimum normal Float value (with specified sign) def minimum_normal(sign=+1) (sign < 0) ? -MIN_N : MIN_N end # minimum subnormal (denormalized) Float value (with specified sign) def minimum_subnormal(sign=+1) (sign < 0) ? -MAX_D : MAX_D end # minimum (subnormal) nonzero Float value, with specified sign def minimum_nonzero(sign=+1) (sign < 0) ? -MIN_D : MIN_D end # maximum finite Float value, with specified sign def maximum_finite(sign=+1) (sign < 0) ? -MAX : MAX end def build(sign, coeff, exp) Math.ldexp(sign*coeff, exp) end def new(*args) args = *args if args.size==1 && args.first.is_a?(Array) if args.size==3 Math.ldexp(args[0]*args[1],args[2]) elsif args.size==2 Math.ldexp(args[0],args[1]) else Float(*args) end end def Num(*args) self.new(*args) end def precision MANT_DIG end # detect actual rounding mode def rounding BigFloat::Support.detect_float_rounding end def emin MIN_EXP-1 end def emax MAX_EXP-1 end def etiny MIN_EXP - MANT_DIG end def etop MAX_EXP - MANT_DIG end end end Remove Float#zero? definition (it's already defined in the core lib) # Native Ruby Float extemsions # Here we add some of the methods available in BinFloat to Float. # # The set of constants with Float metadata is also augmented. # The built-in contantas are: # Note that this uses the "fractional significand" interpretation, # i.e. the significand has the radix point before its first digit. # # Float::RADIX : b = Radix of exponent representation,2 # # Float::MANT_DIG : p = bits (base-RADIX digits) in the significand # # Float::DIG : q = Number of decimal digits such that any floating-point number with q # decimal digits can be rounded into a floating-point number with p radix b # digits and back again without change to the q decimal digits, # q = p * log10(b) if b is a power of 10 # q = floor((p - 1) * log10(b)) otherwise # ((Float::MANT_DIG-1)*Math.log(FLoat::RADIX)/Math.log(10)).floor # # Float::MIN_EXP : emin = Minimum int x such that Float::RADIX**(x-1) is a normalized float # # Float::MIN_10_EXP : Minimum negative integer such that 10 raised to that power is in the # range of normalized floating-point numbers, # ceil(log10(b) * (emin - 1)) # # Float::MAX_EXP : emax = Maximum int x such that Float::RADIX**(x-1) is a representable float # # Float::MAX_10_EXP : Maximum integer such that 10 raised to that power is in the range of # representable finite floating-point numbers, # floor(log10((1 - b**-p) * b**emax)) # # Float::MAX : Maximum representable finite floating-point number # (1 - b**-p) * b**emax # # Float::EPSILON : The difference between 1 and the least value greater than 1 that is # representable in the given floating point type # b**(1-p) # Math.ldexp(*Math.frexp(1).collect{|e| e.kind_of?(Integer) ? e-(Float::MANT_DIG-1) : e}) # # Float::MIN : Minimum normalized positive floating-point number # b**(emin - 1). # # Float::ROUNDS : Addition rounds to 0: zero, 1: nearest, 2: +inf, 3: -inf, -1: unknown. # # Additional contants defined here: # # Float::DECIMAL_DIG : Number of decimal digits, n, such that any floating-point number can be rounded # to a floating-point number with n decimal digits and back again without # change to the value, # pmax * log10(b) if b is a power of 10 # ceil(1 + pmax * log10(b)) otherwise # DECIMAL_DIG = (MANT_DIG*Math.log(RADIX)/Math.log(10)).ceil+1 # # Float::MIN_N : Minimum normalized number == MAX_D.next == MIN # # Float::MAX_D : Maximum denormal number == MIN_N.prev # # Float::MIN_D : Minimum non zero positive denormal number == 0.0.next # # Float::MAX_F : Maximum significand # class Float DECIMAL_DIG = (MANT_DIG*Math.log(RADIX)/Math.log(10)).ceil+1 # Compute the adjacent floating point values: largest value not larger than # this and smallest not smaller. def neighbours f,e = Math.frexp(self) e = Float::MIN_EXP if f==0 e = [Float::MIN_EXP,e].max dx = Math.ldexp(1,e-Float::MANT_DIG) #Math.ldexp(Math.ldexp(1.0,-Float::MANT_DIG),e) min_f = 0.5 #0.5==Math.ldexp(2**(bits-1),-Float::MANT_DIG) max_f = 1.0 - Math.ldexp(1,-Float::MANT_DIG) if f==max_f high = self + dx*2 elsif f==-min_f && e!=Float::MIN_EXP high = self + dx/2 else high = self + dx end if e==Float::MIN_EXP || f!=min_f low = self - dx elsif f==-max_f high = self - dx*2 else low = self - dx/2 end [low, high] end # Previous floating point value def prev neighbours[0] end # Next floating point value; e.g. 1.0.next == 1.0+Float::EPSILON def next neighbours[1] end # Synonym of next, named in the style of Decimal (GDA) def next_plus self.next end # Synonym of prev, named in the style of Decimal (GDA) def next_minus self.prev end def next_toward(other) comparison = self <=> other return self.copy_sign(other) if comparison == 0 if comparison == -1 result = self.next_plus(context) else # comparison == 1 result = self.next_minus(context) end end # Sign: -1 for minus, +1 for plus, nil for nan (note that Float zero is signed) def sign if nan? nil elsif self==0 self.to_s[0,1] == "-" ? -1 : +1 else self < 0 ? -1 : +1 end end # Return copy of self with the sign of other def copy_sign(other) self_sign = self.sign other_sign = other.sign if self_sign && other_sign if self_sign == other_sign self else -self end else nan end end # Returns the internal representation of the number, composed of: # * a sign which is +1 for plus and -1 for minus # * a coefficient (significand) which is a nonnegative integer # * an exponent (an integer) or :inf, :nan or :snan for special values # The value of non-special numbers is sign*coefficient*10^exponent def split sign = self.sign if nan? exp = :nan elsif infinite? exp = :inf else coeff,exp = Math.frexp(self) coeff = Math.ldexp(coeff,Float::MANT_DIG).to_i exp -= Float::MANT_DIG end [sign, coeff, exp] end def int_exp end # Return the value of the number as an signed integer and a scale. def to_int_scale if special? nil else coeff,exp = Math.frexp(x) coeff = Math.ldexp(coeff,Float::MANT_DIG).to_i, exp -= Float::MANT_DIG [coeff, exp] end end # Minimum normalized number == MAX_D.next MIN_N = Math.ldexp(0.5,Float::MIN_EXP) # == nxt(MAX_D) == Float::MIN # Maximum denormal number == MIN_N.prev MAX_D = Math.ldexp(Math.ldexp(1,Float::MANT_DIG-1)-1,Float::MIN_EXP-Float::MANT_DIG) # Minimum non zero positive denormal number == 0.0.next MIN_D = Math.ldexp(1,Float::MIN_EXP-Float::MANT_DIG); # Maximum significand == Math.ldexp(Math.ldexp(1,Float::MANT_DIG)-1,-Float::MANT_DIG) MAX_F = Math.frexp(Float::MAX)[0] == Math.ldexp(Math.ldexp(1,Float::MANT_DIG)-1,-Float::MANT_DIG) # ulp (unit in the last place) according to the definition proposed by J.M. Muller in # "On the definition of ulp(x)" INRIA No. 5504 def ulp(mode=:low) return self if nan? x = abs if x < Math.ldexp(1,MIN_EXP) # x < RADIX*MIN_N Math.ldexp(1,MIN_EXP-MANT_DIG) # res = MIN_D elsif x > MAX # x > Math.ldexp(1-Math.ldexp(1,-MANT_DIG),MAX_EXP) Math.ldexp(1,MAX_EXP-MANT_DIG) # res = MAX - MAX.prev else f,e = Math.frexp(x) e -= 1 if f==Math.ldexp(1,-1) if mode==:low # assign the smaller ulp to radix powers Math.ldexp(1,e-MANT_DIG) end end def special? nan? || infinite? end def normal? if special? || zero? false else self.abs >= MIN_N end end def subnormal? if special? || zero? false else self.abs < MIN_N end end class <<self def radix Float::RADIX end # NaN (not a number value) def nan 0.0/0.0 end # zero value with specified sign def zero(sign=+1) (sign < 0) ? -0.0 : 0.0 end # infinitie value with specified sign def infinite(sign=+1) (sign < 0) ? -1.0/0.0 : 1.0/0.0 end # This provides an common interface (with BigFloat classes) to precision, rounding, etc. def context self end # This is the difference between 1.0 and the smallest floating-point # value greater than 1.0, radix_power(1-significand_precision) # # We have: # Float.epsilon == (1.0.next-1.0) def epsilon(sign=+1) (sign < 0) ? -EPSILON : EPSILON end # The strict epsilon is the smallest value that produces something different from 1.0 # wehen added to 1.0. It may be smaller than the general epsilon, because # of the particular rounding rules used with the floating point format. # This is only meaningful when well-defined rules are used for rounding the result # of floating-point addition. # # We have: # (Float.strict_epsilon+1.0) == 1.0.next # (Float.strict_epsilon.prev+1.0) == 1.0 def strict_epsilon(sign=+1, round=nil) # We don't rely on Float::ROUNDS eps = minimum_nonzero if (1.0+eps) > 1.0 eps else f,e = Math.frexp(1) eps = Math.ldexp(f.next,e-MANT_DIG) if (1.0+eps) > 1.0 eps else eps = Math.ldexp(f,e-MANT_DIG) if (1.0+eps) > 1.0 eps else puts "here" puts "f=#{f} e=#{e} exp=#{e-MANT_DIG} => #{Math.ldexp(f,e-MANT_DIG)} eps = #{epsilon}" Math.ldexp(f,e-MANT_DIG+1) end end end end # This is the maximum relative error corresponding to 1/2 ulp: # (radix/2)*radix_power(-significand_precision) == epsilon/2 # This is called "machine epsilon" in [Goldberg] # We have: # # Float.half_epsilon == 0.5*Float.epsilon def half_epsilon(sign=+1) # 0.5*epsilon(sign) f,e = Math.frexp(1) Math.ldexp(f, e-MANT_DIG) end # minimum normal Float value (with specified sign) def minimum_normal(sign=+1) (sign < 0) ? -MIN_N : MIN_N end # minimum subnormal (denormalized) Float value (with specified sign) def minimum_subnormal(sign=+1) (sign < 0) ? -MAX_D : MAX_D end # minimum (subnormal) nonzero Float value, with specified sign def minimum_nonzero(sign=+1) (sign < 0) ? -MIN_D : MIN_D end # maximum finite Float value, with specified sign def maximum_finite(sign=+1) (sign < 0) ? -MAX : MAX end def build(sign, coeff, exp) Math.ldexp(sign*coeff, exp) end def new(*args) args = *args if args.size==1 && args.first.is_a?(Array) if args.size==3 Math.ldexp(args[0]*args[1],args[2]) elsif args.size==2 Math.ldexp(args[0],args[1]) else Float(*args) end end def Num(*args) self.new(*args) end def precision MANT_DIG end # detect actual rounding mode def rounding BigFloat::Support.detect_float_rounding end def emin MIN_EXP-1 end def emax MAX_EXP-1 end def etiny MIN_EXP - MANT_DIG end def etop MAX_EXP - MANT_DIG end end end
# # = bio/db/pdb/pdb.rb - PDB database class for PDB file format # # Copyright:: Copyright (C) 2003-2006 # GOTO Naohisa <ngoto@gen-info.osaka-u.ac.jp> # Alex Gutteridge <alexg@ebi.ac.uk> # License:: LGPL # # $Id: pdb.rb,v 1.17 2007/03/27 16:29:32 ngoto Exp $ # #-- # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #++ # # = About Bio::PDB # # Please refer document of Bio::PDB class. # # = References # # * ((<URL:http://www.rcsb.org/pdb/>)) # * PDB File Format Contents Guide Version 2.2 (20 December 1996) # ((<URL:http://www.rcsb.org/pdb/file_formats/pdb/pdbguide2.2/guide2.2_frame.html>)) # # = *** CAUTION *** # This is beta version. Specs shall be changed frequently. # require 'bio/db/pdb' require 'bio/data/aa' module Bio # This is the main PDB class which takes care of parsing, annotations # and is the entry way to the co-ordinate data held in models. # # There are many related classes. # # Bio::PDB::Model # Bio::PDB::Chain # Bio::PDB::Residue # Bio::PDB::Heterogen # Bio::PDB::Record::ATOM # Bio::PDB::Record::HETATM # Bio::PDB::Record::* # Bio::PDB::Coordinate # class PDB include Utils include AtomFinder include ResidueFinder include ChainFinder include ModelFinder include HetatmFinder include HeterogenFinder include Enumerable # delimiter for reading via Bio::FlatFile DELIMITER = RS = nil # 1 file 1 entry # Modules required by the field definitions module DataType Pdb_Continuation = nil module Pdb_Integer def self.new(str) str.to_i end end module Pdb_SList def self.new(str) str.to_s.strip.split(/\;\s*/) end end module Pdb_List def self.new(str) str.to_s.strip.split(/\,\s*/) end end module Pdb_Specification_list def self.new(str) a = str.to_s.strip.split(/\;\s*/) a.collect! { |x| x.split(/\:\s*/, 2) } a end end module Pdb_String def self.new(str) str.to_s.gsub(/\s+\z/, '') end #Creates a new module with a string left justified to the #length given in nn def self.[](nn) m = Module.new m.module_eval %Q{ @@nn = nn def self.new(str) str.to_s.gsub(/\s+\z/, '').ljust(@@nn)[0, @@nn] end } m end end #module Pdb_String module Pdb_LString def self.[](nn) m = Module.new m.module_eval %Q{ @@nn = nn def self.new(str) str.to_s.ljust(@@nn)[0, @@nn] end } m end def self.new(str) String.new(str) end end module Pdb_Real def self.[](fmt) m = Module.new m.module_eval %Q{ @@format = fmt def self.new(str) str.to_f end } m end def self.new(str) str.to_f end end module Pdb_StringRJ def self.new(str) str.to_s.gsub(/\A\s+/, '') end end Pdb_Date = Pdb_String Pdb_IDcode = Pdb_String Pdb_Residue_name = Pdb_String Pdb_SymOP = Pdb_String Pdb_Atom = Pdb_String Pdb_AChar = Pdb_String Pdb_Character = Pdb_LString module ConstLikeMethod def Pdb_LString(nn) Pdb_LString[nn] end def Pdb_String(nn) Pdb_String[nn] end def Pdb_Real(fmt) Pdb_Real[fmt] end end #module ConstLikeMethod end #module DataType # The ancestor of every single PDB record class. # It inherits <code>Struct</code> class. # Basically, each line of a PDB file corresponds to # an instance of each corresponding child class. # If continuation exists, multiple lines may correspond to # single instance. # class Record < Struct include DataType extend DataType::ConstLikeMethod # Internal use only. # # parse filed definitions. def self.parse_field_definitions(ary) symbolhash = {} symbolary = [] cont = false # For each field definition (range(start, end), type,symbol) ary.each do |x| range = (x[0] - 1)..(x[1] - 1) # If type is nil (Pdb_Continuation) then set 'cont' to the range # (other wise it is false to indicate no continuation unless x[2] then cont = range else klass = x[2] sym = x[3] # If the symbol is a proper symbol then... if sym.is_a?(Symbol) then # ..if we have the symbol already in the symbol hash # then add the range onto the range array if symbolhash.has_key?(sym) then symbolhash[sym][1] << range else # Other wise put a new symbol in with its type and range # range is given its own array. You can have # anumber of ranges. symbolhash[sym] = [ klass, [ range ] ] symbolary << sym end end end end #each [ symbolhash, symbolary, cont ] end private_class_method :parse_field_definitions # Creates new class by given field definition # The difference from new_direct() is the class # created by the method does lazy evaluation. # # Internal use only. def self.def_rec(*ary) symbolhash, symbolary, cont = parse_field_definitions(ary) klass = Class.new(self.new(*symbolary)) klass.module_eval { @definition = ary @symbols = symbolhash @cont = cont } klass.module_eval { symbolary.each do |x| define_method(x) { do_parse; super } end } klass end #def self.def_rec # creates new class which inherits given class. def self.new_inherit(klass) newklass = Class.new(klass) newklass.module_eval { @definition = klass.module_eval { @definition } @symbols = klass.module_eval { @symbols } @cont = klass.module_eval { @cont } } newklass end # Creates new class by given field definition. # # Internal use only. def self.new_direct(*ary) symbolhash, symbolary, cont = parse_field_definitions(ary) if cont raise 'continuation not allowed. please use def_rec instead' end klass = Class.new(self.new(*symbolary)) klass.module_eval { @definition = ary @symbols = symbolhash @cont = cont } klass.module_eval { define_method(:initialize_from_string) { |str| r = super do_parse r } } klass end #def self.new_direct # symbols def self.symbols #p self @symbols end # Returns true if this record has a field type which allows # continuations. def self.continue? @cont end # Returns true if this record has a field type which allows # continuations. def continue? self.class.continue? end # yields the symbol(k), type(x[0]) and array of ranges # of each symbol. def each_symbol self.class.symbols.each do |k, x| yield k, x[0], x[1] end end # Return original string (except that "\n" are truncated) # for this record (usually just @str, but # sometimes add on the continuation data from other lines. # Returns an array of string. # def original_data if defined?(@cont_data) then [ @str, *@cont_data ] else [ @str ] end end # initialize this record from the given string. # <em>str</em> must be a line (in PDB format). # # You can add continuation lines later using # <code>add_continuation</code> method. def initialize_from_string(str) @str = str @record_name = fetch_record_name(str) @parsed = false self end #-- # Called when we need to access the data, takes the string # and the array of FieldDefs and parses it out. #++ # In order to speeding up processing of PDB file format, # fields have not been parsed before calling this method. # # Normally, it is automatically called and you don't explicitly # need to call it . # def do_parse return self if @parsed str = @str each_symbol do |key, klass, ranges| #If we only have one range then pull that out #and store it in the hash if ranges.size <= 1 then self[key] = klass.new(str[ranges.first]) else #Go through each range and add the string to an array #set the hash key to point to that array ary = [] ranges.each do |r| ary << klass.new(str[r]) unless str[r].to_s.strip.empty? end self[key] = ary end end #each_symbol #If we have continuations then for each line of extra data... if defined?(@cont_data) then @cont_data.each do |str| #Get the symbol, type and range array each_symbol do |key, klass, ranges| #If there's one range then grab that range if ranges.size <= 1 then r = ranges.first unless str[r].to_s.strip.empty? #and concatenate the new data onto the old v = klass.new(str[r]) self[key].concat(v) if self[key] != v end else #If there's more than one range then add to the array ary = self[key] ranges.each do |r| ary << klass.new(str[r]) unless str[r].to_s.strip.empty? end end end end end @parsed = true self end # fetches record name def fetch_record_name(str) str[0..5].strip end private :fetch_record_name # fetches record name def self.fetch_record_name(str) str[0..5].strip end private_class_method :fetch_record_name # If given <em>str</em> can be the continuation of the current record, # then return the order number of the continuation associated with # the Pdb_Continuation field definition. # Otherwise, returns -1. def fetch_cont(str) (c = continue?) ? str[c].to_i : -1 end private :fetch_cont # Record name of this record, e.g. "HEADER", "ATOM". def record_name @record_name or self.class.to_s.split(/\:\:/)[-1].to_s.upcase end # keeping compatibility with old version alias record_type record_name # Internal use only. # # Adds continuation data to the record from str if str is # really the continuation of current record. # Returns self (= not nil) if str is the continuation. # Otherwaise, returns false. # def add_continuation(str) #Check that this record can continue #and that str has the same type and definition return false unless self.continue? return false unless fetch_record_name(str) == @record_name return false unless self.class.get_record_class(str) == self.class return false unless fetch_cont(str) >= 2 #If all this is OK then add onto @cont_data unless defined?(@cont_data) @cont_data = [] end @cont_data << str # Returns self (= not nil) if succeeded. self end # creates definition hash from current classes constants def self.create_definition_hash hash = {} constants.each do |x| hash[x] = const_get(x) if /\A[A-Z][A-Z0-9]+\z/ =~ x end if x = const_get(:Default) then hash.default = x end hash end # same as Struct#inspect. # # Note that <code>do_parse</code> is automatically called # before <code>inspect</code>. # # (Warning: The do_parse might sweep hidden bugs in PDB classes.) def inspect do_parse super end #-- # # definitions # contains all the rules for parsing each field # based on format V 2.2, 16-DEC-1996 # # http://www.rcsb.org/pdb/docs/format/pdbguide2.2/guide2.2_frame.html # http://www.rcsb.org/pdb/docs/format/pdbguide2.2/Contents_Guide_21.html # # Details of following data are taken from these documents. # [ 1..6, :Record_name, nil ], # XXXXXX = # new([ start, end, type of data, symbol to access ], ...) # #++ # HEADER record class HEADER = def_rec([ 11, 50, Pdb_String, :classification ], #Pdb_String(40) [ 51, 59, Pdb_Date, :depDate ], [ 63, 66, Pdb_IDcode, :idCode ] ) # OBSLTE record class OBSLTE = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 12, 20, Pdb_Date, :repDate ], [ 22, 25, Pdb_IDcode, :idCode ], [ 32, 35, Pdb_IDcode, :rIdCode ], [ 37, 40, Pdb_IDcode, :rIdCode ], [ 42, 45, Pdb_IDcode, :rIdCode ], [ 47, 50, Pdb_IDcode, :rIdCode ], [ 52, 55, Pdb_IDcode, :rIdCode ], [ 57, 60, Pdb_IDcode, :rIdCode ], [ 62, 65, Pdb_IDcode, :rIdCode ], [ 67, 70, Pdb_IDcode, :rIdCode ] ) # TITLE record class TITLE = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 11, 70, Pdb_String, :title ] ) # CAVEAT record class CAVEAT = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 12, 15, Pdb_IDcode, :idcode ], [ 20, 70, Pdb_String, :comment ] ) # COMPND record class COMPND = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 11, 70, Pdb_Specification_list, :compound ] ) # SOURCE record class SOURCE = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 11, 70, Pdb_Specification_list, :srcName ] ) # KEYWDS record class KEYWDS = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 11, 70, Pdb_List, :keywds ] ) # EXPDTA record class EXPDTA = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 11, 70, Pdb_SList, :technique ] ) # AUTHOR record class AUTHOR = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 11, 70, Pdb_List, :authorList ] ) # REVDAT record class REVDAT = def_rec([ 8, 10, Pdb_Integer, :modNum ], [ 11, 12, Pdb_Continuation, nil ], [ 14, 22, Pdb_Date, :modDate ], [ 24, 28, Pdb_String, :modId ], # Pdb_String(5) [ 32, 32, Pdb_Integer, :modType ], [ 40, 45, Pdb_LString(6), :record ], [ 47, 52, Pdb_LString(6), :record ], [ 54, 59, Pdb_LString(6), :record ], [ 61, 66, Pdb_LString(6), :record ] ) # SPRSDE record class SPRSDE = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 12, 20, Pdb_Date, :sprsdeDate ], [ 22, 25, Pdb_IDcode, :idCode ], [ 32, 35, Pdb_IDcode, :sIdCode ], [ 37, 40, Pdb_IDcode, :sIdCode ], [ 42, 45, Pdb_IDcode, :sIdCode ], [ 47, 50, Pdb_IDcode, :sIdCode ], [ 52, 55, Pdb_IDcode, :sIdCode ], [ 57, 60, Pdb_IDcode, :sIdCode ], [ 62, 65, Pdb_IDcode, :sIdCode ], [ 67, 70, Pdb_IDcode, :sIdCode ] ) # 'JRNL' is defined below JRNL = nil # 'REMARK' is defined below REMARK = nil # DBREF record class DBREF = def_rec([ 8, 11, Pdb_IDcode, :idCode ], [ 13, 13, Pdb_Character, :chainID ], [ 15, 18, Pdb_Integer, :seqBegin ], [ 19, 19, Pdb_AChar, :insertBegin ], [ 21, 24, Pdb_Integer, :seqEnd ], [ 25, 25, Pdb_AChar, :insertEnd ], [ 27, 32, Pdb_String, :database ], #Pdb_LString [ 34, 41, Pdb_String, :dbAccession ], #Pdb_LString [ 43, 54, Pdb_String, :dbIdCode ], #Pdb_LString [ 56, 60, Pdb_Integer, :dbseqBegin ], [ 61, 61, Pdb_AChar, :idbnsBeg ], [ 63, 67, Pdb_Integer, :dbseqEnd ], [ 68, 68, Pdb_AChar, :dbinsEnd ] ) # SEQADV record class SEQADV = def_rec([ 8, 11, Pdb_IDcode, :idCode ], [ 13, 15, Pdb_Residue_name, :resName ], [ 17, 17, Pdb_Character, :chainID ], [ 19, 22, Pdb_Integer, :seqNum ], [ 23, 23, Pdb_AChar, :iCode ], [ 25, 28, Pdb_String, :database ], #Pdb_LString [ 30, 38, Pdb_String, :dbIdCode ], #Pdb_LString [ 40, 42, Pdb_Residue_name, :dbRes ], [ 44, 48, Pdb_Integer, :dbSeq ], [ 50, 70, Pdb_LString, :conflict ] ) # SEQRES record class SEQRES = def_rec(#[ 9, 10, Pdb_Integer, :serNum ], [ 9, 10, Pdb_Continuation, nil ], [ 12, 12, Pdb_Character, :chainID ], [ 14, 17, Pdb_Integer, :numRes ], [ 20, 22, Pdb_Residue_name, :resName ], [ 24, 26, Pdb_Residue_name, :resName ], [ 28, 30, Pdb_Residue_name, :resName ], [ 32, 34, Pdb_Residue_name, :resName ], [ 36, 38, Pdb_Residue_name, :resName ], [ 40, 42, Pdb_Residue_name, :resName ], [ 44, 46, Pdb_Residue_name, :resName ], [ 48, 50, Pdb_Residue_name, :resName ], [ 52, 54, Pdb_Residue_name, :resName ], [ 56, 58, Pdb_Residue_name, :resName ], [ 60, 62, Pdb_Residue_name, :resName ], [ 64, 66, Pdb_Residue_name, :resName ], [ 68, 70, Pdb_Residue_name, :resName ] ) # MODRS record class MODRES = def_rec([ 8, 11, Pdb_IDcode, :idCode ], [ 13, 15, Pdb_Residue_name, :resName ], [ 17, 17, Pdb_Character, :chainID ], [ 19, 22, Pdb_Integer, :seqNum ], [ 23, 23, Pdb_AChar, :iCode ], [ 25, 27, Pdb_Residue_name, :stdRes ], [ 30, 70, Pdb_String, :comment ] ) # HET record class HET = def_rec([ 8, 10, Pdb_LString(3), :hetID ], [ 13, 13, Pdb_Character, :ChainID ], [ 14, 17, Pdb_Integer, :seqNum ], [ 18, 18, Pdb_AChar, :iCode ], [ 21, 25, Pdb_Integer, :numHetAtoms ], [ 31, 70, Pdb_String, :text ] ) # HETNAM record class HETNAM = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 12, 14, Pdb_LString(3), :hetID ], [ 16, 70, Pdb_String, :text ] ) # HETSYN record class HETSYN = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 12, 14, Pdb_LString(3), :hetID ], [ 16, 70, Pdb_SList, :hetSynonyms ] ) # FORMUL record class FORMUL = def_rec([ 9, 10, Pdb_Integer, :compNum ], [ 13, 15, Pdb_LString(3), :hetID ], [ 17, 18, Pdb_Integer, :continuation ], [ 19, 19, Pdb_Character, :asterisk ], [ 20, 70, Pdb_String, :text ] ) # HELIX record class HELIX = def_rec([ 8, 10, Pdb_Integer, :serNum ], #[ 12, 14, Pdb_LString(3), :helixID ], [ 12, 14, Pdb_StringRJ, :helixID ], [ 16, 18, Pdb_Residue_name, :initResName ], [ 20, 20, Pdb_Character, :initChainID ], [ 22, 25, Pdb_Integer, :initSeqNum ], [ 26, 26, Pdb_AChar, :initICode ], [ 28, 30, Pdb_Residue_name, :endResName ], [ 32, 32, Pdb_Character, :endChainID ], [ 34, 37, Pdb_Integer, :endSeqNum ], [ 38, 38, Pdb_AChar, :endICode ], [ 39, 40, Pdb_Integer, :helixClass ], [ 41, 70, Pdb_String, :comment ], [ 72, 76, Pdb_Integer, :length ] ) # SHEET record class SHEET = def_rec([ 8, 10, Pdb_Integer, :strand ], #[ 12, 14, Pdb_LString(3), :sheetID ], [ 12, 14, Pdb_StringRJ, :sheetID ], [ 15, 16, Pdb_Integer, :numStrands ], [ 18, 20, Pdb_Residue_name, :initResName ], [ 22, 22, Pdb_Character, :initChainID ], [ 23, 26, Pdb_Integer, :initSeqNum ], [ 27, 27, Pdb_AChar, :initICode ], [ 29, 31, Pdb_Residue_name, :endResName ], [ 33, 33, Pdb_Character, :endChainID ], [ 34, 37, Pdb_Integer, :endSeqNum ], [ 38, 38, Pdb_AChar, :endICode ], [ 39, 40, Pdb_Integer, :sense ], [ 42, 45, Pdb_Atom, :curAtom ], [ 46, 48, Pdb_Residue_name, :curResName ], [ 50, 50, Pdb_Character, :curChainId ], [ 51, 54, Pdb_Integer, :curResSeq ], [ 55, 55, Pdb_AChar, :curICode ], [ 57, 60, Pdb_Atom, :prevAtom ], [ 61, 63, Pdb_Residue_name, :prevResName ], [ 65, 65, Pdb_Character, :prevChainId ], [ 66, 69, Pdb_Integer, :prevResSeq ], [ 70, 70, Pdb_AChar, :prevICode ] ) # TURN record class TURN = def_rec([ 8, 10, Pdb_Integer, :seq ], #[ 12, 14, Pdb_LString(3), :turnId ], [ 12, 14, Pdb_StringRJ, :turnId ], [ 16, 18, Pdb_Residue_name, :initResName ], [ 20, 20, Pdb_Character, :initChainId ], [ 21, 24, Pdb_Integer, :initSeqNum ], [ 25, 25, Pdb_AChar, :initICode ], [ 27, 29, Pdb_Residue_name, :endResName ], [ 31, 31, Pdb_Character, :endChainId ], [ 32, 35, Pdb_Integer, :endSeqNum ], [ 36, 36, Pdb_AChar, :endICode ], [ 41, 70, Pdb_String, :comment ] ) # SSBOND record class SSBOND = def_rec([ 8, 10, Pdb_Integer, :serNum ], [ 12, 14, Pdb_LString(3), :pep1 ], # "CYS" [ 16, 16, Pdb_Character, :chainID1 ], [ 18, 21, Pdb_Integer, :seqNum1 ], [ 22, 22, Pdb_AChar, :icode1 ], [ 26, 28, Pdb_LString(3), :pep2 ], # "CYS" [ 30, 30, Pdb_Character, :chainID2 ], [ 32, 35, Pdb_Integer, :seqNum2 ], [ 36, 36, Pdb_AChar, :icode2 ], [ 60, 65, Pdb_SymOP, :sym1 ], [ 67, 72, Pdb_SymOP, :sym2 ] ) # LINK record class LINK = def_rec([ 13, 16, Pdb_Atom, :name1 ], [ 17, 17, Pdb_Character, :altLoc1 ], [ 18, 20, Pdb_Residue_name, :resName1 ], [ 22, 22, Pdb_Character, :chainID1 ], [ 23, 26, Pdb_Integer, :resSeq1 ], [ 27, 27, Pdb_AChar, :iCode1 ], [ 43, 46, Pdb_Atom, :name2 ], [ 47, 47, Pdb_Character, :altLoc2 ], [ 48, 50, Pdb_Residue_name, :resName2 ], [ 52, 52, Pdb_Character, :chainID2 ], [ 53, 56, Pdb_Integer, :resSeq2 ], [ 57, 57, Pdb_AChar, :iCode2 ], [ 60, 65, Pdb_SymOP, :sym1 ], [ 67, 72, Pdb_SymOP, :sym2 ] ) # HYDBND record class HYDBND = def_rec([ 13, 16, Pdb_Atom, :name1 ], [ 17, 17, Pdb_Character, :altLoc1 ], [ 18, 20, Pdb_Residue_name, :resName1 ], [ 22, 22, Pdb_Character, :Chain1 ], [ 23, 27, Pdb_Integer, :resSeq1 ], [ 28, 28, Pdb_AChar, :ICode1 ], [ 30, 33, Pdb_Atom, :nameH ], [ 34, 34, Pdb_Character, :altLocH ], [ 36, 36, Pdb_Character, :ChainH ], [ 37, 41, Pdb_Integer, :resSeqH ], [ 42, 42, Pdb_AChar, :iCodeH ], [ 44, 47, Pdb_Atom, :name2 ], [ 48, 48, Pdb_Character, :altLoc2 ], [ 49, 51, Pdb_Residue_name, :resName2 ], [ 53, 53, Pdb_Character, :chainID2 ], [ 54, 58, Pdb_Integer, :resSeq2 ], [ 59, 59, Pdb_AChar, :iCode2 ], [ 60, 65, Pdb_SymOP, :sym1 ], [ 67, 72, Pdb_SymOP, :sym2 ] ) # SLTBRG record class SLTBRG = def_rec([ 13, 16, Pdb_Atom, :atom1 ], [ 17, 17, Pdb_Character, :altLoc1 ], [ 18, 20, Pdb_Residue_name, :resName1 ], [ 22, 22, Pdb_Character, :chainID1 ], [ 23, 26, Pdb_Integer, :resSeq1 ], [ 27, 27, Pdb_AChar, :iCode1 ], [ 43, 46, Pdb_Atom, :atom2 ], [ 47, 47, Pdb_Character, :altLoc2 ], [ 48, 50, Pdb_Residue_name, :resName2 ], [ 52, 52, Pdb_Character, :chainID2 ], [ 53, 56, Pdb_Integer, :resSeq2 ], [ 57, 57, Pdb_AChar, :iCode2 ], [ 60, 65, Pdb_SymOP, :sym1 ], [ 67, 72, Pdb_SymOP, :sym2 ] ) # CISPEP record class CISPEP = def_rec([ 8, 10, Pdb_Integer, :serNum ], [ 12, 14, Pdb_LString(3), :pep1 ], [ 16, 16, Pdb_Character, :chainID1 ], [ 18, 21, Pdb_Integer, :seqNum1 ], [ 22, 22, Pdb_AChar, :icode1 ], [ 26, 28, Pdb_LString(3), :pep2 ], [ 30, 30, Pdb_Character, :chainID2 ], [ 32, 35, Pdb_Integer, :seqNum2 ], [ 36, 36, Pdb_AChar, :icode2 ], [ 44, 46, Pdb_Integer, :modNum ], [ 54, 59, Pdb_Real('6.2'), :measure ] ) # SITE record class SITE = def_rec([ 8, 10, Pdb_Integer, :seqNum ], [ 12, 14, Pdb_LString(3), :siteID ], [ 16, 17, Pdb_Integer, :numRes ], [ 19, 21, Pdb_Residue_name, :resName1 ], [ 23, 23, Pdb_Character, :chainID1 ], [ 24, 27, Pdb_Integer, :seq1 ], [ 28, 28, Pdb_AChar, :iCode1 ], [ 30, 32, Pdb_Residue_name, :resName2 ], [ 34, 34, Pdb_Character, :chainID2 ], [ 35, 38, Pdb_Integer, :seq2 ], [ 39, 39, Pdb_AChar, :iCode2 ], [ 41, 43, Pdb_Residue_name, :resName3 ], [ 45, 45, Pdb_Character, :chainID3 ], [ 46, 49, Pdb_Integer, :seq3 ], [ 50, 50, Pdb_AChar, :iCode3 ], [ 52, 54, Pdb_Residue_name, :resName4 ], [ 56, 56, Pdb_Character, :chainID4 ], [ 57, 60, Pdb_Integer, :seq4 ], [ 61, 61, Pdb_AChar, :iCode4 ] ) # CRYST1 record class CRYST1 = def_rec([ 7, 15, Pdb_Real('9.3'), :a ], [ 16, 24, Pdb_Real('9.3'), :b ], [ 25, 33, Pdb_Real('9.3'), :c ], [ 34, 40, Pdb_Real('7.2'), :alpha ], [ 41, 47, Pdb_Real('7.2'), :beta ], [ 48, 54, Pdb_Real('7.2'), :gamma ], [ 56, 66, Pdb_LString, :sGroup ], [ 67, 70, Pdb_Integer, :z ] ) # ORIGX1 record class # # ORIGXn n=1, 2, or 3 ORIGX1 = def_rec([ 11, 20, Pdb_Real('10.6'), :On1 ], [ 21, 30, Pdb_Real('10.6'), :On2 ], [ 31, 40, Pdb_Real('10.6'), :On3 ], [ 46, 55, Pdb_Real('10.5'), :Tn ] ) # ORIGX2 record class ORIGX2 = new_inherit(ORIGX1) # ORIGX3 record class ORIGX3 = new_inherit(ORIGX1) # SCALE1 record class # # SCALEn n=1, 2, or 3 SCALE1 = def_rec([ 11, 20, Pdb_Real('10.6'), :Sn1 ], [ 21, 30, Pdb_Real('10.6'), :Sn2 ], [ 31, 40, Pdb_Real('10.6'), :Sn3 ], [ 46, 55, Pdb_Real('10.5'), :Un ] ) # SCALE2 record class SCALE2 = new_inherit(SCALE1) # SCALE3 record class SCALE3 = new_inherit(SCALE1) # MTRIX1 record class # # MTRIXn n=1,2, or 3 MTRIX1 = def_rec([ 8, 10, Pdb_Integer, :serial ], [ 11, 20, Pdb_Real('10.6'), :Mn1 ], [ 21, 30, Pdb_Real('10.6'), :Mn2 ], [ 31, 40, Pdb_Real('10.6'), :Mn3 ], [ 46, 55, Pdb_Real('10.5'), :Vn ], [ 60, 60, Pdb_Integer, :iGiven ] ) # MTRIX2 record class MTRIX2 = new_inherit(MTRIX1) # MTRIX3 record class MTRIX3 = new_inherit(MTRIX1) # TVECT record class TVECT = def_rec([ 8, 10, Pdb_Integer, :serial ], [ 11, 20, Pdb_Real('10.5'), :t1 ], [ 21, 30, Pdb_Real('10.5'), :t2 ], [ 31, 40, Pdb_Real('10.5'), :t3 ], [ 41, 70, Pdb_String, :text ] ) # MODEL record class MODEL = def_rec([ 11, 14, Pdb_Integer, :serial ] ) # ChangeLog: model_serial are changed to serial # ATOM record class ATOM = new_direct([ 7, 11, Pdb_Integer, :serial ], [ 13, 16, Pdb_Atom, :name ], [ 17, 17, Pdb_Character, :altLoc ], [ 18, 20, Pdb_Residue_name, :resName ], [ 22, 22, Pdb_Character, :chainID ], [ 23, 26, Pdb_Integer, :resSeq ], [ 27, 27, Pdb_AChar, :iCode ], [ 31, 38, Pdb_Real('8.3'), :x ], [ 39, 46, Pdb_Real('8.3'), :y ], [ 47, 54, Pdb_Real('8.3'), :z ], [ 55, 60, Pdb_Real('6.2'), :occupancy ], [ 61, 66, Pdb_Real('6.2'), :tempFactor ], [ 73, 76, Pdb_LString(4), :segID ], [ 77, 78, Pdb_LString(2), :element ], [ 79, 80, Pdb_LString(2), :charge ] ) # ATOM record class class ATOM include Utils include Comparable # for backward compatibility alias occ occupancy # for backward compatibility alias bfac tempFactor # residue the atom belongs to. attr_accessor :residue # SIGATM record attr_accessor :sigatm # ANISOU record attr_accessor :anisou # TER record attr_accessor :ter #Returns a Coordinate class instance of the xyz positions def xyz Coordinate[ x, y, z ] end #Returns an array of the xyz positions def to_a [ x, y, z ] end #Sorts based on serial numbers def <=>(other) return serial <=> other.serial end def do_parse return self if @parsed self.serial = @str[6..10].to_i self.name = @str[12..15].strip self.altLoc = @str[16..16] self.resName = @str[17..19].strip self.chainID = @str[21..21] self.resSeq = @str[22..25].to_i self.iCode = @str[26..26].strip self.x = @str[30..37].to_f self.y = @str[38..45].to_f self.z = @str[46..53].to_f self.occupancy = @str[54..59].to_f self.tempFactor = @str[60..65].to_f self.segID = @str[72..75].to_s.rstrip self.element = @str[76..77].to_s.lstrip self.charge = @str[78..79].to_s.strip @parsed = true self end def justify_atomname atomname = self.name.to_s return atomname[0, 4] if atomname.length >= 4 case atomname.length when 0 return ' ' when 1 return ' ' + atomname + ' ' when 2 if /\A[0-9]/ =~ atomname then return sprintf('%-4s', atomname) elsif /[0-9]\z/ =~ atomname then return sprintf(' %-3s', atomname) end when 3 if /\A[0-9]/ =~ atomname then return sprintf('%-4s', atomname) end end # ambiguous case for two- or three-letter name elem = self.element.to_s.strip if elem.size > 0 and i = atomname.index(elem) then if i == 0 and elem.size == 1 then return sprintf(' %-3s', atomname) else return sprintf('%-4s', atomname) end end if self.class == HETATM then if /\A(B[^AEHIKR]|C[^ADEFLMORSU]|F[^EMR]|H[^EFGOS]|I[^NR]|K[^R]|N[^ABDEIOP]|O[^S]|P[^ABDMORTU]|S[^BCEGIMNR]|V|W|Y[^B])/ =~ atomname then return sprintf(' %-3s', atomname) else return sprintf('%-4s', atomname) end else # ATOM if /\A[CHONS]/ =~ atomname then return sprintf(' %-3s', atomname) else return sprintf('%-4s', atomname) end end # could not be reached here raise 'bug!' end private :justify_atomname def to_s atomname = justify_atomname sprintf("%-6s%5d %-4s%-1s%3s %-1s%4d%-1s %8.3f%8.3f%8.3f%6.2f%6.2f %-4s%2s%-2s\n", self.record_name, self.serial, atomname, self.altLoc, self.resName, self.chainID, self.resSeq, self.iCode, self.x, self.y, self.z, self.occupancy, self.tempFactor, self.segID, self.element, self.charge) end end #class ATOM # SIGATM record class SIGATM = def_rec([ 7, 11, Pdb_Integer, :serial ], [ 13, 16, Pdb_Atom, :name ], [ 17, 17, Pdb_Character, :altLoc ], [ 18, 20, Pdb_Residue_name, :resName ], [ 22, 22, Pdb_Character, :chainID ], [ 23, 26, Pdb_Integer, :resSeq ], [ 27, 27, Pdb_AChar, :iCode ], [ 31, 38, Pdb_Real('8.3'), :sigX ], [ 39, 46, Pdb_Real('8.3'), :sigY ], [ 47, 54, Pdb_Real('8.3'), :sigZ ], [ 55, 60, Pdb_Real('6.2'), :sigOcc ], [ 61, 66, Pdb_Real('6.2'), :sigTemp ], [ 73, 76, Pdb_LString(4), :segID ], [ 77, 78, Pdb_LString(2), :element ], [ 79, 80, Pdb_LString(2), :charge ] ) # ANISOU record class ANISOU = def_rec([ 7, 11, Pdb_Integer, :serial ], [ 13, 16, Pdb_Atom, :name ], [ 17, 17, Pdb_Character, :altLoc ], [ 18, 20, Pdb_Residue_name, :resName ], [ 22, 22, Pdb_Character, :chainID ], [ 23, 26, Pdb_Integer, :resSeq ], [ 27, 27, Pdb_AChar, :iCode ], [ 29, 35, Pdb_Integer, :U11 ], [ 36, 42, Pdb_Integer, :U22 ], [ 43, 49, Pdb_Integer, :U33 ], [ 50, 56, Pdb_Integer, :U12 ], [ 57, 63, Pdb_Integer, :U13 ], [ 64, 70, Pdb_Integer, :U23 ], [ 73, 76, Pdb_LString(4), :segID ], [ 77, 78, Pdb_LString(2), :element ], [ 79, 80, Pdb_LString(2), :charge ] ) # ANISOU record class class ANISOU # SIGUIJ record attr_accessor :siguij end #class ANISOU # SIGUIJ record class SIGUIJ = def_rec([ 7, 11, Pdb_Integer, :serial ], [ 13, 16, Pdb_Atom, :name ], [ 17, 17, Pdb_Character, :altLoc ], [ 18, 20, Pdb_Residue_name, :resName ], [ 22, 22, Pdb_Character, :chainID ], [ 23, 26, Pdb_Integer, :resSeq ], [ 27, 27, Pdb_AChar, :iCode ], [ 29, 35, Pdb_Integer, :SigmaU11 ], [ 36, 42, Pdb_Integer, :SigmaU22 ], [ 43, 49, Pdb_Integer, :SigmaU33 ], [ 50, 56, Pdb_Integer, :SigmaU12 ], [ 57, 63, Pdb_Integer, :SigmaU13 ], [ 64, 70, Pdb_Integer, :SigmaU23 ], [ 73, 76, Pdb_LString(4), :segID ], [ 77, 78, Pdb_LString(2), :element ], [ 79, 80, Pdb_LString(2), :charge ] ) # TER record class TER = def_rec([ 7, 11, Pdb_Integer, :serial ], [ 18, 20, Pdb_Residue_name, :resName ], [ 22, 22, Pdb_Character, :chainID ], [ 23, 26, Pdb_Integer, :resSeq ], [ 27, 27, Pdb_AChar, :iCode ] ) #HETATM = # new_direct([ 7, 11, Pdb_Integer, :serial ], # [ 13, 16, Pdb_Atom, :name ], # [ 17, 17, Pdb_Character, :altLoc ], # [ 18, 20, Pdb_Residue_name, :resName ], # [ 22, 22, Pdb_Character, :chainID ], # [ 23, 26, Pdb_Integer, :resSeq ], # [ 27, 27, Pdb_AChar, :iCode ], # [ 31, 38, Pdb_Real('8.3'), :x ], # [ 39, 46, Pdb_Real('8.3'), :y ], # [ 47, 54, Pdb_Real('8.3'), :z ], # [ 55, 60, Pdb_Real('6.2'), :occupancy ], # [ 61, 66, Pdb_Real('6.2'), :tempFactor ], # [ 73, 76, Pdb_LString(4), :segID ], # [ 77, 78, Pdb_LString(2), :element ], # [ 79, 80, Pdb_LString(2), :charge ] # ) # HETATM record class HETATM = new_inherit(ATOM) # HETATM record class. # It inherits ATOM class. class HETATM; end # ENDMDL record class ENDMDL = def_rec([ 2, 1, Pdb_Integer, :serial ] # dummy field (always 0) ) # CONECT record class CONECT = def_rec([ 7, 11, Pdb_Integer, :serial ], [ 12, 16, Pdb_Integer, :serial ], [ 17, 21, Pdb_Integer, :serial ], [ 22, 26, Pdb_Integer, :serial ], [ 27, 31, Pdb_Integer, :serial ], [ 32, 36, Pdb_Integer, :serial ], [ 37, 41, Pdb_Integer, :serial ], [ 42, 46, Pdb_Integer, :serial ], [ 47, 51, Pdb_Integer, :serial ], [ 52, 56, Pdb_Integer, :serial ], [ 57, 61, Pdb_Integer, :serial ] ) # MASTER record class MASTER = def_rec([ 11, 15, Pdb_Integer, :numRemark ], [ 16, 20, Pdb_Integer, "0" ], [ 21, 25, Pdb_Integer, :numHet ], [ 26, 30, Pdb_Integer, :numHelix ], [ 31, 35, Pdb_Integer, :numSheet ], [ 36, 40, Pdb_Integer, :numTurn ], [ 41, 45, Pdb_Integer, :numSite ], [ 46, 50, Pdb_Integer, :numXform ], [ 51, 55, Pdb_Integer, :numCoord ], [ 56, 60, Pdb_Integer, :numTer ], [ 61, 65, Pdb_Integer, :numConect ], [ 66, 70, Pdb_Integer, :numSeq ] ) # JRNL record classes class Jrnl < self # subrecord of JRNL # 13, 16 # JRNL AUTH record class AUTH = def_rec([ 13, 16, Pdb_String, :sub_record ], # "AUTH" [ 17, 18, Pdb_Continuation, nil ], [ 20, 70, Pdb_List, :authorList ] ) # JRNL TITL record class TITL = def_rec([ 13, 16, Pdb_String, :sub_record ], # "TITL" [ 17, 18, Pdb_Continuation, nil ], [ 20, 70, Pdb_LString, :title ] ) # JRNL EDIT record class EDIT = def_rec([ 13, 16, Pdb_String, :sub_record ], # "EDIT" [ 17, 18, Pdb_Continuation, nil ], [ 20, 70, Pdb_List, :editorList ] ) # JRNL REF record class REF = def_rec([ 13, 16, Pdb_String, :sub_record ], # "REF" [ 17, 18, Pdb_Continuation, nil ], [ 20, 47, Pdb_LString, :pubName ], [ 50, 51, Pdb_LString(2), "V." ], [ 52, 55, Pdb_String, :volume ], [ 57, 61, Pdb_String, :page ], [ 63, 66, Pdb_Integer, :year ] ) # JRNL PUBL record class PUBL = def_rec([ 13, 16, Pdb_String, :sub_record ], # "PUBL" [ 17, 18, Pdb_Continuation, nil ], [ 20, 70, Pdb_LString, :pub ] ) # JRNL REFN record class REFN = def_rec([ 13, 16, Pdb_String, :sub_record ], # "REFN" [ 20, 23, Pdb_LString(4), "ASTM" ], [ 25, 30, Pdb_LString(6), :astm ], [ 33, 34, Pdb_LString(2), :country ], [ 36, 39, Pdb_LString(4), :BorS ], # "ISBN" or "ISSN" [ 41, 65, Pdb_LString, :isbn ], [ 67, 70, Pdb_LString(4), :coden ] # "0353" for unpublished ) # default or unknown record # Default = def_rec([ 13, 16, Pdb_String, :sub_record ]) # "" # definitions (hash) Definition = create_definition_hash end #class JRNL # REMARK record classes for REMARK 1 class Remark1 < self # 13, 16 # REMARK 1 REFERENCE record class EFER = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "1" [ 12, 20, Pdb_String, :sub_record ], # "REFERENCE" [ 22, 70, Pdb_Integer, :refNum ] ) # REMARK 1 AUTH record class AUTH = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "1" [ 13, 16, Pdb_String, :sub_record ], # "AUTH" [ 17, 18, Pdb_Continuation, nil ], [ 20, 70, Pdb_List, :authorList ] ) # REMARK 1 TITL record class TITL = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "1" [ 13, 16, Pdb_String, :sub_record ], # "TITL" [ 17, 18, Pdb_Continuation, nil ], [ 20, 70, Pdb_LString, :title ] ) # REMARK 1 EDIT record class EDIT = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "1" [ 13, 16, Pdb_String, :sub_record ], # "EDIT" [ 17, 18, Pdb_Continuation, nil ], [ 20, 70, Pdb_LString, :editorList ] ) # REMARK 1 REF record class REF = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "1" [ 13, 16, Pdb_LString(3), :sub_record ], # "REF" [ 17, 18, Pdb_Continuation, nil ], [ 20, 47, Pdb_LString, :pubName ], [ 50, 51, Pdb_LString(2), "V." ], [ 52, 55, Pdb_String, :volume ], [ 57, 61, Pdb_String, :page ], [ 63, 66, Pdb_Integer, :year ] ) # REMARK 1 PUBL record class PUBL = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "1" [ 13, 16, Pdb_String, :sub_record ], # "PUBL" [ 17, 18, Pdb_Continuation, nil ], [ 20, 70, Pdb_LString, :pub ] ) # REMARK 1 REFN record class REFN = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "1" [ 13, 16, Pdb_String, :sub_record ], # "REFN" [ 20, 23, Pdb_LString(4), "ASTM" ], [ 25, 30, Pdb_LString, :astm ], [ 33, 34, Pdb_LString, :country ], [ 36, 39, Pdb_LString(4), :BorS ], [ 41, 65, Pdb_LString, :isbn ], [ 68, 70, Pdb_LString(4), :coden ] ) # default (or unknown) record class for REMARK 1 Default = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "1" [ 13, 16, Pdb_String, :sub_record ] # "" ) # definitions (hash) Definition = create_definition_hash end #class Remark1 # REMARK record classes for REMARK 2 class Remark2 < self # 29, 38 == 'ANGSTROMS.' ANGSTROMS = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "2" [ 12, 22, Pdb_LString(11), :sub_record ], # "RESOLUTION." [ 23, 27, Pdb_Real('5.2'), :resolution ], [ 29, 38, Pdb_LString(10), "ANGSTROMS." ] ) # 23, 38 == ' NOT APPLICABLE.' NOT_APPLICABLE = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "2" [ 12, 22, Pdb_LString(11), :sub_record ], # "RESOLUTION." [ 23, 38, Pdb_LString(16), :resolution ], # " NOT APPLICABLE." [ 41, 70, Pdb_String, :comment ] ) # others Default = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "2" [ 12, 22, Pdb_LString(11), :sub_record ], # "RESOLUTION." [ 24, 70, Pdb_String, :comment ] ) end #class Remark2 # REMARK record class for REMARK n (n>=3) RemarkN = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], [ 12, 70, Pdb_LString, :text ] ) # default (or unknown) record class Default = def_rec([ 8, 70, Pdb_LString, :text ]) # definitions (hash) Definition = create_definition_hash # END record class. # # Because END is a reserved word of Ruby, it is separately # added to the hash End = def_rec([ 2, 1, Pdb_Integer, :serial ]) # dummy field (always 0) Definition['END'] = End # Basically just look up the class in Definition hash # do some munging for JRNL and REMARK def self.get_record_class(str) t = fetch_record_name(str) if d = Definition[t] then return d end case t when 'JRNL' d = Jrnl::Definition[str[12..15].to_s.strip] when 'REMARK' case str[7..9].to_i when 1 d = Remark1::Definition[str[12..15].to_s.strip] when 2 if str[28..37] == 'ANGSTROMS.' then d = Remark2::ANGSTROMS elsif str[22..37] == ' NOT APPLICABLE.' then d = Remark2::NOT_APPLICABLE else d = Remark2::Default end else d = RemarkN end else # unknown field d = Default end return d end end #class Record Coordinate_fileds = { 'MODEL' => true, 'ENDMDL' => true, 'ATOM' => true, 'HETATM' => true, 'SIGATM' => true, 'SIGUIJ' => true, 'ANISOU' => true, 'TER' => true, } # Creates a new Bio::PDB object from given <em>str</em>. def initialize(str) #Aha! Our entry into the world of PDB parsing, we initialise a PDB #object with the whole PDB file as a string #each PDB has an array of the lines of the original file #a bit memory-tastic! A hash of records and an array of models #also has an id @data = str.split(/[\r\n]+/) @hash = {} @models = [] @id = nil #Flag to say whether the current line is part of a continuation cont = false #Empty current model cModel = Model.new cChain = nil #Chain.new cResidue = nil #Residue.new cLigand = nil #Heterogen.new c_atom = nil #Goes through each line and replace that line with a PDB::Record @data.collect! do |line| #Go to next if the previous line was contiunation able, and #add_continuation returns true. Line is added by add_continuation next if cont and cont = cont.add_continuation(line) #Make the new record f = Record.get_record_class(line).new.initialize_from_string(line) #p f #Set cont cont = f if f.continue? #Set the hash to point to this record either by adding to an #array, or on it's own key = f.record_name if a = @hash[key] then a << f else @hash[key] = [ f ] end # Do something for ATOM and HETATM if key == 'ATOM' or key == 'HETATM' then if cChain and f.chainID == cChain.id chain = cChain else if chain = cModel[f.chainID] cChain = chain unless cChain else # If we don't have chain, add a new chain newChain = Chain.new(f.chainID, cModel) cModel.addChain(newChain) cChain = newChain chain = newChain end end end case key when 'ATOM' c_atom = f residueID = Residue.get_residue_id_from_atom(f) if cResidue and residueID == cResidue.id residue = cResidue else if residue = chain.get_residue_by_id(residueID) cResidue = residue unless cResidue else # add a new residue newResidue = Residue.new(f.resName, f.resSeq, f.iCode, chain) chain.addResidue(newResidue) cResidue = newResidue residue = newResidue end end f.residue = residue residue.addAtom(f) when 'HETATM' c_atom = f residueID = Heterogen.get_residue_id_from_atom(f) if cLigand and residueID == cLigand.id ligand = cLigand else if ligand = chain.get_heterogen_by_id(residueID) cLigand = ligand unless cLigand else # add a new heterogen newLigand = Heterogen.new(f.resName, f.resSeq, f.iCode, chain) chain.addLigand(newLigand) cLigand = newLigand ligand = newLigand #Each model has a special solvent chain. (for compatibility) if f.resName == 'HOH' cModel.addSolvent(newLigand) end end end f.residue = ligand ligand.addAtom(f) when 'MODEL' c_atom = nil if cModel.model_serial or cModel.chains.size > 0 then self.addModel(cModel) end cModel = Model.new(f.serial) when 'TER' if c_atom c_atom.ter = f else #$stderr.puts "Warning: stray TER?" end when 'SIGATM' if c_atom #$stderr.puts "Warning: duplicated SIGATM?" if c_atom.sigatm c_atom.sigatm = f else #$stderr.puts "Warning: stray SIGATM?" end when 'ANISOU' if c_atom #$stderr.puts "Warning: duplicated ANISOU?" if c_atom.anisou c_atom.anisou = f else #$stderr.puts "Warning: stray ANISOU?" end when 'SIGUIJ' if c_atom and c_atom.anisou #$stderr.puts "Warning: duplicated SIGUIJ?" if c_atom.anisou.siguij c_atom.anisou.siguij = f else #$stderr.puts "Warning: stray SIGUIJ?" end else c_atom = nil end f end #each #At the end we need to add the final model self.addModel(cModel) @data.compact! end #def initialize # all records in this entry as an array. attr_reader :data # all records in this entry as an hash accessed by record names. attr_reader :hash # models in this entry (array). attr_reader :models # Adds a <code>Bio::Model</code> object to the current strucutre. # Adds a model to the current structure. # Returns self. def addModel(model) raise "Expecting a Bio::PDB::Model" if not model.is_a? Bio::PDB::Model @models.push(model) self end # Iterates over each model. # Iterates over each of the models in the structure. # Returns <code>self</code>. def each @models.each{ |model| yield model } self end # Alias needed for Bio::PDB::ModelFinder alias each_model each # Provides keyed access to the models based on serial number # returns nil if it's not there def [](key) @models.find{ |model| key == model.model_serial } end #-- # (should it raise an exception?) #++ #-- #Stringifies to a list of atom records - we could add the annotation #as well if needed #++ # Returns a string of Bio::PDB::Models. This propogates down the heirarchy # till you get to Bio::PDB::Record::ATOM which are outputed in PDB format def to_s string = "" @models.each{ |model| string << model.to_s } string << "END\n" return string end #Makes a hash out of an array of PDB::Records and some kind of symbol #.__send__ invokes the method specified by the symbol. #Essentially it ends up with a hash with keys given in the sub_record #Not sure I fully understand this def make_hash(ary, meth) h = {} ary.each do |f| k = f.__send__(meth) h[k] = [] unless h.has_key?(k) h[k] << f end h end private :make_hash #Takes an array and returns another array of PDB::Records def make_grouping(ary, meth) a = [] k_prev = nil ary.each do |f| k = f.__send__(meth) if k_prev and k_prev == k then a.last << f else a << [] a.last << f end k_prev = k end a end private :make_grouping # Gets all records whose record type is _name_. # Returns an array of <code>Bio::PDB::Record::*</code> objects. # # if _name_ is nil, returns hash storing all record data. # # Example: # p pdb.record('HETATM') # p pdb.record['HETATM'] # def record(name = nil) name ? @hash[name] : @hash end #-- # PDB original methods #Returns a hash of the REMARK records based on the remarkNum #++ # Gets REMARK records. # If no arguments, it returns all REMARK records as a hash. # If remark number is specified, returns only corresponding REMARK records. # If number == 1 or 2 ("REMARK 1" or "REMARK 2"), returns an array # of Bio::PDB::Record instances. Otherwise, returns an array of strings. # def remark(nn = nil) unless defined?(@remark) h = make_hash(self.record('REMARK'), :remarkNum) h.each do |i, a| a.shift # remove first record (= space only) if i != 1 and i != 2 then a.collect! { |f| f.text.gsub(/\s+\z/, '') } end end @remark = h end nn ? @remark[nn] : @remark end # Gets JRNL records. # If no arguments, it returns all JRNL records as a hash. # If sub record name is specified, it returns only corresponding records # as an array of Bio::PDB::Record instances. # def jrnl(sub_record = nil) unless defined?(@jrnl) @jrnl = make_hash(self.record('JRNL'), :sub_record) end sub_record ? @jrnl[sub_record] : @jrnl end #-- #Finding methods - just grabs the record with the appropriate id #or returns and array of all of them #++ # Gets HELIX records. # If no arguments are given, it returns all HELIX records. # (Returns an array of <code>Bio::PDB::Record::HELIX</code> instances.) # If <em>helixID</em> is given, it only returns records # corresponding to given <em>helixID</em>. # (Returns an <code>Bio::PDB::Record::HELIX</code> instance.) # def helix(helixID = nil) if helixID then self.record('HELIX').find { |f| f.helixID == helixID } else self.record('HELIX') end end # Gets TURN records. # If no arguments are given, it returns all TURN records. # (Returns an array of <code>Bio::PDB::Record::TURN</code> instances.) # If <em>turnId</em> is given, it only returns a record # corresponding to given <em>turnId</em>. # (Returns an <code>Bio::PDB::Record::TURN</code> instance.) # def turn(turnId = nil) if turnId then self.record('TURN').find { |f| f.turnId == turnId } else self.record('TURN') end end # Gets SHEET records. # If no arguments are given, it returns all SHEET records # as an array of arrays of <code>Bio::PDB::Record::SHEET</code> instances. # If <em>sheetID</em> is given, it returns an array of # <code>Bio::PDB::Record::SHEET</code> instances. def sheet(sheetID = nil) unless defined?(@sheet) @sheet = make_grouping(self.record('SHEET'), :sheetID) end if sheetID then @sheet.find_all { |f| f.first.sheetID == sheetID } else @sheet end end # Gets SSBOND records. def ssbond self.record('SSBOND') end #-- # Get seqres - we get this to return a nice Bio::Seq object #++ # Amino acid or nucleic acid sequence of backbone residues in "SEQRES". # If <em>chainID</em> is given, it returns corresponding sequence # as an array of string. # Otherwise, returns a hash which contains all sequences. # def seqres(chainID = nil) unless defined?(@seqres) h = make_hash(self.record('SEQRES'), :chainID) newHash = {} h.each do |k, a| a.collect! { |f| f.resName } a.flatten! # determine nuc or aa? tmp = Hash.new(0) a[0,13].each { |x| tmp[x.to_s.strip.size] += 1 } if tmp[3] >= tmp[1] then # amino acid sequence a.collect! do |aa| #aa is three letter code: i.e. ALA #need to look up with Ala aa = aa.capitalize (Bio::AminoAcid.three2one(aa) or 'X') end seq = Bio::Sequence::AA.new(a.to_s) else # nucleic acid sequence a.collect! do |na| na = na.strip na.size == 1 ? na : 'n' end seq = Bio::Sequence::NA.new(a.to_s) end newHash[k] = seq end @seqres = newHash end if chainID then @seqres[chainID] else @seqres end end # Gets DBREF records. # Returns an array of Bio::PDB::Record::DBREF objects. # # If <em>chainID</em> is given, it returns corresponding DBREF records. def dbref(chainID = nil) if chainID then self.record('DBREF').find_all { |f| f.chainID == chainID } else self.record('DBREF') end end # Keywords in "KEYWDS". # Returns an array of string. def keywords self.record('KEYWDS').collect { |f| f.keywds }.flatten end # Classification in "HEADER". def classification self.record('HEADER').first.classification end # Get authors in "AUTHOR". def authors self.record('AUTHOR').first.authorList end #-- # Bio::DB methods #++ # PDB identifier written in "HEADER". (e.g. 1A00) def entry_id @id = self.record('HEADER').first.idCode unless @id @id end # Same as <tt>Bio::PDB#entry_id</tt>. def accession self.entry_id end # Title of this entry in "TITLE". def definition self.record('TITLE').first.title end # Current modification number in "REVDAT". def version self.record('REVDAT').first.modNum end end #class PDB end #module Bio fixed a bug: Bio::PDB::Record::***.new.inspect fails. # # = bio/db/pdb/pdb.rb - PDB database class for PDB file format # # Copyright:: Copyright (C) 2003-2006 # GOTO Naohisa <ngoto@gen-info.osaka-u.ac.jp> # Alex Gutteridge <alexg@ebi.ac.uk> # License:: LGPL # # $Id: pdb.rb,v 1.18 2007/03/27 16:37:33 ngoto Exp $ # #-- # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #++ # # = About Bio::PDB # # Please refer document of Bio::PDB class. # # = References # # * ((<URL:http://www.rcsb.org/pdb/>)) # * PDB File Format Contents Guide Version 2.2 (20 December 1996) # ((<URL:http://www.rcsb.org/pdb/file_formats/pdb/pdbguide2.2/guide2.2_frame.html>)) # # = *** CAUTION *** # This is beta version. Specs shall be changed frequently. # require 'bio/db/pdb' require 'bio/data/aa' module Bio # This is the main PDB class which takes care of parsing, annotations # and is the entry way to the co-ordinate data held in models. # # There are many related classes. # # Bio::PDB::Model # Bio::PDB::Chain # Bio::PDB::Residue # Bio::PDB::Heterogen # Bio::PDB::Record::ATOM # Bio::PDB::Record::HETATM # Bio::PDB::Record::* # Bio::PDB::Coordinate # class PDB include Utils include AtomFinder include ResidueFinder include ChainFinder include ModelFinder include HetatmFinder include HeterogenFinder include Enumerable # delimiter for reading via Bio::FlatFile DELIMITER = RS = nil # 1 file 1 entry # Modules required by the field definitions module DataType Pdb_Continuation = nil module Pdb_Integer def self.new(str) str.to_i end end module Pdb_SList def self.new(str) str.to_s.strip.split(/\;\s*/) end end module Pdb_List def self.new(str) str.to_s.strip.split(/\,\s*/) end end module Pdb_Specification_list def self.new(str) a = str.to_s.strip.split(/\;\s*/) a.collect! { |x| x.split(/\:\s*/, 2) } a end end module Pdb_String def self.new(str) str.to_s.gsub(/\s+\z/, '') end #Creates a new module with a string left justified to the #length given in nn def self.[](nn) m = Module.new m.module_eval %Q{ @@nn = nn def self.new(str) str.to_s.gsub(/\s+\z/, '').ljust(@@nn)[0, @@nn] end } m end end #module Pdb_String module Pdb_LString def self.[](nn) m = Module.new m.module_eval %Q{ @@nn = nn def self.new(str) str.to_s.ljust(@@nn)[0, @@nn] end } m end def self.new(str) String.new(str) end end module Pdb_Real def self.[](fmt) m = Module.new m.module_eval %Q{ @@format = fmt def self.new(str) str.to_f end } m end def self.new(str) str.to_f end end module Pdb_StringRJ def self.new(str) str.to_s.gsub(/\A\s+/, '') end end Pdb_Date = Pdb_String Pdb_IDcode = Pdb_String Pdb_Residue_name = Pdb_String Pdb_SymOP = Pdb_String Pdb_Atom = Pdb_String Pdb_AChar = Pdb_String Pdb_Character = Pdb_LString module ConstLikeMethod def Pdb_LString(nn) Pdb_LString[nn] end def Pdb_String(nn) Pdb_String[nn] end def Pdb_Real(fmt) Pdb_Real[fmt] end end #module ConstLikeMethod end #module DataType # The ancestor of every single PDB record class. # It inherits <code>Struct</code> class. # Basically, each line of a PDB file corresponds to # an instance of each corresponding child class. # If continuation exists, multiple lines may correspond to # single instance. # class Record < Struct include DataType extend DataType::ConstLikeMethod # Internal use only. # # parse filed definitions. def self.parse_field_definitions(ary) symbolhash = {} symbolary = [] cont = false # For each field definition (range(start, end), type,symbol) ary.each do |x| range = (x[0] - 1)..(x[1] - 1) # If type is nil (Pdb_Continuation) then set 'cont' to the range # (other wise it is false to indicate no continuation unless x[2] then cont = range else klass = x[2] sym = x[3] # If the symbol is a proper symbol then... if sym.is_a?(Symbol) then # ..if we have the symbol already in the symbol hash # then add the range onto the range array if symbolhash.has_key?(sym) then symbolhash[sym][1] << range else # Other wise put a new symbol in with its type and range # range is given its own array. You can have # anumber of ranges. symbolhash[sym] = [ klass, [ range ] ] symbolary << sym end end end end #each [ symbolhash, symbolary, cont ] end private_class_method :parse_field_definitions # Creates new class by given field definition # The difference from new_direct() is the class # created by the method does lazy evaluation. # # Internal use only. def self.def_rec(*ary) symbolhash, symbolary, cont = parse_field_definitions(ary) klass = Class.new(self.new(*symbolary)) klass.module_eval { @definition = ary @symbols = symbolhash @cont = cont } klass.module_eval { symbolary.each do |x| define_method(x) { do_parse; super } end } klass end #def self.def_rec # creates new class which inherits given class. def self.new_inherit(klass) newklass = Class.new(klass) newklass.module_eval { @definition = klass.module_eval { @definition } @symbols = klass.module_eval { @symbols } @cont = klass.module_eval { @cont } } newklass end # Creates new class by given field definition. # # Internal use only. def self.new_direct(*ary) symbolhash, symbolary, cont = parse_field_definitions(ary) if cont raise 'continuation not allowed. please use def_rec instead' end klass = Class.new(self.new(*symbolary)) klass.module_eval { @definition = ary @symbols = symbolhash @cont = cont } klass.module_eval { define_method(:initialize_from_string) { |str| r = super do_parse r } } klass end #def self.new_direct # symbols def self.symbols #p self @symbols end # Returns true if this record has a field type which allows # continuations. def self.continue? @cont end # Returns true if this record has a field type which allows # continuations. def continue? self.class.continue? end # yields the symbol(k), type(x[0]) and array of ranges # of each symbol. def each_symbol self.class.symbols.each do |k, x| yield k, x[0], x[1] end end # Return original string (except that "\n" are truncated) # for this record (usually just @str, but # sometimes add on the continuation data from other lines. # Returns an array of string. # def original_data if defined?(@cont_data) then [ @str, *@cont_data ] else [ @str ] end end # initialize this record from the given string. # <em>str</em> must be a line (in PDB format). # # You can add continuation lines later using # <code>add_continuation</code> method. def initialize_from_string(str) @str = str @record_name = fetch_record_name(str) @parsed = false self end #-- # Called when we need to access the data, takes the string # and the array of FieldDefs and parses it out. #++ # In order to speeding up processing of PDB file format, # fields have not been parsed before calling this method. # # Normally, it is automatically called and you don't explicitly # need to call it . # def do_parse return self if @parsed or !@str str = @str each_symbol do |key, klass, ranges| #If we only have one range then pull that out #and store it in the hash if ranges.size <= 1 then self[key] = klass.new(str[ranges.first]) else #Go through each range and add the string to an array #set the hash key to point to that array ary = [] ranges.each do |r| ary << klass.new(str[r]) unless str[r].to_s.strip.empty? end self[key] = ary end end #each_symbol #If we have continuations then for each line of extra data... if defined?(@cont_data) then @cont_data.each do |str| #Get the symbol, type and range array each_symbol do |key, klass, ranges| #If there's one range then grab that range if ranges.size <= 1 then r = ranges.first unless str[r].to_s.strip.empty? #and concatenate the new data onto the old v = klass.new(str[r]) self[key].concat(v) if self[key] != v end else #If there's more than one range then add to the array ary = self[key] ranges.each do |r| ary << klass.new(str[r]) unless str[r].to_s.strip.empty? end end end end end @parsed = true self end # fetches record name def fetch_record_name(str) str[0..5].strip end private :fetch_record_name # fetches record name def self.fetch_record_name(str) str[0..5].strip end private_class_method :fetch_record_name # If given <em>str</em> can be the continuation of the current record, # then return the order number of the continuation associated with # the Pdb_Continuation field definition. # Otherwise, returns -1. def fetch_cont(str) (c = continue?) ? str[c].to_i : -1 end private :fetch_cont # Record name of this record, e.g. "HEADER", "ATOM". def record_name @record_name or self.class.to_s.split(/\:\:/)[-1].to_s.upcase end # keeping compatibility with old version alias record_type record_name # Internal use only. # # Adds continuation data to the record from str if str is # really the continuation of current record. # Returns self (= not nil) if str is the continuation. # Otherwaise, returns false. # def add_continuation(str) #Check that this record can continue #and that str has the same type and definition return false unless self.continue? return false unless fetch_record_name(str) == @record_name return false unless self.class.get_record_class(str) == self.class return false unless fetch_cont(str) >= 2 #If all this is OK then add onto @cont_data unless defined?(@cont_data) @cont_data = [] end @cont_data << str # Returns self (= not nil) if succeeded. self end # creates definition hash from current classes constants def self.create_definition_hash hash = {} constants.each do |x| hash[x] = const_get(x) if /\A[A-Z][A-Z0-9]+\z/ =~ x end if x = const_get(:Default) then hash.default = x end hash end # same as Struct#inspect. # # Note that <code>do_parse</code> is automatically called # before <code>inspect</code>. # # (Warning: The do_parse might sweep hidden bugs in PDB classes.) def inspect do_parse super end #-- # # definitions # contains all the rules for parsing each field # based on format V 2.2, 16-DEC-1996 # # http://www.rcsb.org/pdb/docs/format/pdbguide2.2/guide2.2_frame.html # http://www.rcsb.org/pdb/docs/format/pdbguide2.2/Contents_Guide_21.html # # Details of following data are taken from these documents. # [ 1..6, :Record_name, nil ], # XXXXXX = # new([ start, end, type of data, symbol to access ], ...) # #++ # HEADER record class HEADER = def_rec([ 11, 50, Pdb_String, :classification ], #Pdb_String(40) [ 51, 59, Pdb_Date, :depDate ], [ 63, 66, Pdb_IDcode, :idCode ] ) # OBSLTE record class OBSLTE = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 12, 20, Pdb_Date, :repDate ], [ 22, 25, Pdb_IDcode, :idCode ], [ 32, 35, Pdb_IDcode, :rIdCode ], [ 37, 40, Pdb_IDcode, :rIdCode ], [ 42, 45, Pdb_IDcode, :rIdCode ], [ 47, 50, Pdb_IDcode, :rIdCode ], [ 52, 55, Pdb_IDcode, :rIdCode ], [ 57, 60, Pdb_IDcode, :rIdCode ], [ 62, 65, Pdb_IDcode, :rIdCode ], [ 67, 70, Pdb_IDcode, :rIdCode ] ) # TITLE record class TITLE = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 11, 70, Pdb_String, :title ] ) # CAVEAT record class CAVEAT = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 12, 15, Pdb_IDcode, :idcode ], [ 20, 70, Pdb_String, :comment ] ) # COMPND record class COMPND = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 11, 70, Pdb_Specification_list, :compound ] ) # SOURCE record class SOURCE = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 11, 70, Pdb_Specification_list, :srcName ] ) # KEYWDS record class KEYWDS = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 11, 70, Pdb_List, :keywds ] ) # EXPDTA record class EXPDTA = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 11, 70, Pdb_SList, :technique ] ) # AUTHOR record class AUTHOR = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 11, 70, Pdb_List, :authorList ] ) # REVDAT record class REVDAT = def_rec([ 8, 10, Pdb_Integer, :modNum ], [ 11, 12, Pdb_Continuation, nil ], [ 14, 22, Pdb_Date, :modDate ], [ 24, 28, Pdb_String, :modId ], # Pdb_String(5) [ 32, 32, Pdb_Integer, :modType ], [ 40, 45, Pdb_LString(6), :record ], [ 47, 52, Pdb_LString(6), :record ], [ 54, 59, Pdb_LString(6), :record ], [ 61, 66, Pdb_LString(6), :record ] ) # SPRSDE record class SPRSDE = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 12, 20, Pdb_Date, :sprsdeDate ], [ 22, 25, Pdb_IDcode, :idCode ], [ 32, 35, Pdb_IDcode, :sIdCode ], [ 37, 40, Pdb_IDcode, :sIdCode ], [ 42, 45, Pdb_IDcode, :sIdCode ], [ 47, 50, Pdb_IDcode, :sIdCode ], [ 52, 55, Pdb_IDcode, :sIdCode ], [ 57, 60, Pdb_IDcode, :sIdCode ], [ 62, 65, Pdb_IDcode, :sIdCode ], [ 67, 70, Pdb_IDcode, :sIdCode ] ) # 'JRNL' is defined below JRNL = nil # 'REMARK' is defined below REMARK = nil # DBREF record class DBREF = def_rec([ 8, 11, Pdb_IDcode, :idCode ], [ 13, 13, Pdb_Character, :chainID ], [ 15, 18, Pdb_Integer, :seqBegin ], [ 19, 19, Pdb_AChar, :insertBegin ], [ 21, 24, Pdb_Integer, :seqEnd ], [ 25, 25, Pdb_AChar, :insertEnd ], [ 27, 32, Pdb_String, :database ], #Pdb_LString [ 34, 41, Pdb_String, :dbAccession ], #Pdb_LString [ 43, 54, Pdb_String, :dbIdCode ], #Pdb_LString [ 56, 60, Pdb_Integer, :dbseqBegin ], [ 61, 61, Pdb_AChar, :idbnsBeg ], [ 63, 67, Pdb_Integer, :dbseqEnd ], [ 68, 68, Pdb_AChar, :dbinsEnd ] ) # SEQADV record class SEQADV = def_rec([ 8, 11, Pdb_IDcode, :idCode ], [ 13, 15, Pdb_Residue_name, :resName ], [ 17, 17, Pdb_Character, :chainID ], [ 19, 22, Pdb_Integer, :seqNum ], [ 23, 23, Pdb_AChar, :iCode ], [ 25, 28, Pdb_String, :database ], #Pdb_LString [ 30, 38, Pdb_String, :dbIdCode ], #Pdb_LString [ 40, 42, Pdb_Residue_name, :dbRes ], [ 44, 48, Pdb_Integer, :dbSeq ], [ 50, 70, Pdb_LString, :conflict ] ) # SEQRES record class SEQRES = def_rec(#[ 9, 10, Pdb_Integer, :serNum ], [ 9, 10, Pdb_Continuation, nil ], [ 12, 12, Pdb_Character, :chainID ], [ 14, 17, Pdb_Integer, :numRes ], [ 20, 22, Pdb_Residue_name, :resName ], [ 24, 26, Pdb_Residue_name, :resName ], [ 28, 30, Pdb_Residue_name, :resName ], [ 32, 34, Pdb_Residue_name, :resName ], [ 36, 38, Pdb_Residue_name, :resName ], [ 40, 42, Pdb_Residue_name, :resName ], [ 44, 46, Pdb_Residue_name, :resName ], [ 48, 50, Pdb_Residue_name, :resName ], [ 52, 54, Pdb_Residue_name, :resName ], [ 56, 58, Pdb_Residue_name, :resName ], [ 60, 62, Pdb_Residue_name, :resName ], [ 64, 66, Pdb_Residue_name, :resName ], [ 68, 70, Pdb_Residue_name, :resName ] ) # MODRS record class MODRES = def_rec([ 8, 11, Pdb_IDcode, :idCode ], [ 13, 15, Pdb_Residue_name, :resName ], [ 17, 17, Pdb_Character, :chainID ], [ 19, 22, Pdb_Integer, :seqNum ], [ 23, 23, Pdb_AChar, :iCode ], [ 25, 27, Pdb_Residue_name, :stdRes ], [ 30, 70, Pdb_String, :comment ] ) # HET record class HET = def_rec([ 8, 10, Pdb_LString(3), :hetID ], [ 13, 13, Pdb_Character, :ChainID ], [ 14, 17, Pdb_Integer, :seqNum ], [ 18, 18, Pdb_AChar, :iCode ], [ 21, 25, Pdb_Integer, :numHetAtoms ], [ 31, 70, Pdb_String, :text ] ) # HETNAM record class HETNAM = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 12, 14, Pdb_LString(3), :hetID ], [ 16, 70, Pdb_String, :text ] ) # HETSYN record class HETSYN = def_rec([ 9, 10, Pdb_Continuation, nil ], [ 12, 14, Pdb_LString(3), :hetID ], [ 16, 70, Pdb_SList, :hetSynonyms ] ) # FORMUL record class FORMUL = def_rec([ 9, 10, Pdb_Integer, :compNum ], [ 13, 15, Pdb_LString(3), :hetID ], [ 17, 18, Pdb_Integer, :continuation ], [ 19, 19, Pdb_Character, :asterisk ], [ 20, 70, Pdb_String, :text ] ) # HELIX record class HELIX = def_rec([ 8, 10, Pdb_Integer, :serNum ], #[ 12, 14, Pdb_LString(3), :helixID ], [ 12, 14, Pdb_StringRJ, :helixID ], [ 16, 18, Pdb_Residue_name, :initResName ], [ 20, 20, Pdb_Character, :initChainID ], [ 22, 25, Pdb_Integer, :initSeqNum ], [ 26, 26, Pdb_AChar, :initICode ], [ 28, 30, Pdb_Residue_name, :endResName ], [ 32, 32, Pdb_Character, :endChainID ], [ 34, 37, Pdb_Integer, :endSeqNum ], [ 38, 38, Pdb_AChar, :endICode ], [ 39, 40, Pdb_Integer, :helixClass ], [ 41, 70, Pdb_String, :comment ], [ 72, 76, Pdb_Integer, :length ] ) # SHEET record class SHEET = def_rec([ 8, 10, Pdb_Integer, :strand ], #[ 12, 14, Pdb_LString(3), :sheetID ], [ 12, 14, Pdb_StringRJ, :sheetID ], [ 15, 16, Pdb_Integer, :numStrands ], [ 18, 20, Pdb_Residue_name, :initResName ], [ 22, 22, Pdb_Character, :initChainID ], [ 23, 26, Pdb_Integer, :initSeqNum ], [ 27, 27, Pdb_AChar, :initICode ], [ 29, 31, Pdb_Residue_name, :endResName ], [ 33, 33, Pdb_Character, :endChainID ], [ 34, 37, Pdb_Integer, :endSeqNum ], [ 38, 38, Pdb_AChar, :endICode ], [ 39, 40, Pdb_Integer, :sense ], [ 42, 45, Pdb_Atom, :curAtom ], [ 46, 48, Pdb_Residue_name, :curResName ], [ 50, 50, Pdb_Character, :curChainId ], [ 51, 54, Pdb_Integer, :curResSeq ], [ 55, 55, Pdb_AChar, :curICode ], [ 57, 60, Pdb_Atom, :prevAtom ], [ 61, 63, Pdb_Residue_name, :prevResName ], [ 65, 65, Pdb_Character, :prevChainId ], [ 66, 69, Pdb_Integer, :prevResSeq ], [ 70, 70, Pdb_AChar, :prevICode ] ) # TURN record class TURN = def_rec([ 8, 10, Pdb_Integer, :seq ], #[ 12, 14, Pdb_LString(3), :turnId ], [ 12, 14, Pdb_StringRJ, :turnId ], [ 16, 18, Pdb_Residue_name, :initResName ], [ 20, 20, Pdb_Character, :initChainId ], [ 21, 24, Pdb_Integer, :initSeqNum ], [ 25, 25, Pdb_AChar, :initICode ], [ 27, 29, Pdb_Residue_name, :endResName ], [ 31, 31, Pdb_Character, :endChainId ], [ 32, 35, Pdb_Integer, :endSeqNum ], [ 36, 36, Pdb_AChar, :endICode ], [ 41, 70, Pdb_String, :comment ] ) # SSBOND record class SSBOND = def_rec([ 8, 10, Pdb_Integer, :serNum ], [ 12, 14, Pdb_LString(3), :pep1 ], # "CYS" [ 16, 16, Pdb_Character, :chainID1 ], [ 18, 21, Pdb_Integer, :seqNum1 ], [ 22, 22, Pdb_AChar, :icode1 ], [ 26, 28, Pdb_LString(3), :pep2 ], # "CYS" [ 30, 30, Pdb_Character, :chainID2 ], [ 32, 35, Pdb_Integer, :seqNum2 ], [ 36, 36, Pdb_AChar, :icode2 ], [ 60, 65, Pdb_SymOP, :sym1 ], [ 67, 72, Pdb_SymOP, :sym2 ] ) # LINK record class LINK = def_rec([ 13, 16, Pdb_Atom, :name1 ], [ 17, 17, Pdb_Character, :altLoc1 ], [ 18, 20, Pdb_Residue_name, :resName1 ], [ 22, 22, Pdb_Character, :chainID1 ], [ 23, 26, Pdb_Integer, :resSeq1 ], [ 27, 27, Pdb_AChar, :iCode1 ], [ 43, 46, Pdb_Atom, :name2 ], [ 47, 47, Pdb_Character, :altLoc2 ], [ 48, 50, Pdb_Residue_name, :resName2 ], [ 52, 52, Pdb_Character, :chainID2 ], [ 53, 56, Pdb_Integer, :resSeq2 ], [ 57, 57, Pdb_AChar, :iCode2 ], [ 60, 65, Pdb_SymOP, :sym1 ], [ 67, 72, Pdb_SymOP, :sym2 ] ) # HYDBND record class HYDBND = def_rec([ 13, 16, Pdb_Atom, :name1 ], [ 17, 17, Pdb_Character, :altLoc1 ], [ 18, 20, Pdb_Residue_name, :resName1 ], [ 22, 22, Pdb_Character, :Chain1 ], [ 23, 27, Pdb_Integer, :resSeq1 ], [ 28, 28, Pdb_AChar, :ICode1 ], [ 30, 33, Pdb_Atom, :nameH ], [ 34, 34, Pdb_Character, :altLocH ], [ 36, 36, Pdb_Character, :ChainH ], [ 37, 41, Pdb_Integer, :resSeqH ], [ 42, 42, Pdb_AChar, :iCodeH ], [ 44, 47, Pdb_Atom, :name2 ], [ 48, 48, Pdb_Character, :altLoc2 ], [ 49, 51, Pdb_Residue_name, :resName2 ], [ 53, 53, Pdb_Character, :chainID2 ], [ 54, 58, Pdb_Integer, :resSeq2 ], [ 59, 59, Pdb_AChar, :iCode2 ], [ 60, 65, Pdb_SymOP, :sym1 ], [ 67, 72, Pdb_SymOP, :sym2 ] ) # SLTBRG record class SLTBRG = def_rec([ 13, 16, Pdb_Atom, :atom1 ], [ 17, 17, Pdb_Character, :altLoc1 ], [ 18, 20, Pdb_Residue_name, :resName1 ], [ 22, 22, Pdb_Character, :chainID1 ], [ 23, 26, Pdb_Integer, :resSeq1 ], [ 27, 27, Pdb_AChar, :iCode1 ], [ 43, 46, Pdb_Atom, :atom2 ], [ 47, 47, Pdb_Character, :altLoc2 ], [ 48, 50, Pdb_Residue_name, :resName2 ], [ 52, 52, Pdb_Character, :chainID2 ], [ 53, 56, Pdb_Integer, :resSeq2 ], [ 57, 57, Pdb_AChar, :iCode2 ], [ 60, 65, Pdb_SymOP, :sym1 ], [ 67, 72, Pdb_SymOP, :sym2 ] ) # CISPEP record class CISPEP = def_rec([ 8, 10, Pdb_Integer, :serNum ], [ 12, 14, Pdb_LString(3), :pep1 ], [ 16, 16, Pdb_Character, :chainID1 ], [ 18, 21, Pdb_Integer, :seqNum1 ], [ 22, 22, Pdb_AChar, :icode1 ], [ 26, 28, Pdb_LString(3), :pep2 ], [ 30, 30, Pdb_Character, :chainID2 ], [ 32, 35, Pdb_Integer, :seqNum2 ], [ 36, 36, Pdb_AChar, :icode2 ], [ 44, 46, Pdb_Integer, :modNum ], [ 54, 59, Pdb_Real('6.2'), :measure ] ) # SITE record class SITE = def_rec([ 8, 10, Pdb_Integer, :seqNum ], [ 12, 14, Pdb_LString(3), :siteID ], [ 16, 17, Pdb_Integer, :numRes ], [ 19, 21, Pdb_Residue_name, :resName1 ], [ 23, 23, Pdb_Character, :chainID1 ], [ 24, 27, Pdb_Integer, :seq1 ], [ 28, 28, Pdb_AChar, :iCode1 ], [ 30, 32, Pdb_Residue_name, :resName2 ], [ 34, 34, Pdb_Character, :chainID2 ], [ 35, 38, Pdb_Integer, :seq2 ], [ 39, 39, Pdb_AChar, :iCode2 ], [ 41, 43, Pdb_Residue_name, :resName3 ], [ 45, 45, Pdb_Character, :chainID3 ], [ 46, 49, Pdb_Integer, :seq3 ], [ 50, 50, Pdb_AChar, :iCode3 ], [ 52, 54, Pdb_Residue_name, :resName4 ], [ 56, 56, Pdb_Character, :chainID4 ], [ 57, 60, Pdb_Integer, :seq4 ], [ 61, 61, Pdb_AChar, :iCode4 ] ) # CRYST1 record class CRYST1 = def_rec([ 7, 15, Pdb_Real('9.3'), :a ], [ 16, 24, Pdb_Real('9.3'), :b ], [ 25, 33, Pdb_Real('9.3'), :c ], [ 34, 40, Pdb_Real('7.2'), :alpha ], [ 41, 47, Pdb_Real('7.2'), :beta ], [ 48, 54, Pdb_Real('7.2'), :gamma ], [ 56, 66, Pdb_LString, :sGroup ], [ 67, 70, Pdb_Integer, :z ] ) # ORIGX1 record class # # ORIGXn n=1, 2, or 3 ORIGX1 = def_rec([ 11, 20, Pdb_Real('10.6'), :On1 ], [ 21, 30, Pdb_Real('10.6'), :On2 ], [ 31, 40, Pdb_Real('10.6'), :On3 ], [ 46, 55, Pdb_Real('10.5'), :Tn ] ) # ORIGX2 record class ORIGX2 = new_inherit(ORIGX1) # ORIGX3 record class ORIGX3 = new_inherit(ORIGX1) # SCALE1 record class # # SCALEn n=1, 2, or 3 SCALE1 = def_rec([ 11, 20, Pdb_Real('10.6'), :Sn1 ], [ 21, 30, Pdb_Real('10.6'), :Sn2 ], [ 31, 40, Pdb_Real('10.6'), :Sn3 ], [ 46, 55, Pdb_Real('10.5'), :Un ] ) # SCALE2 record class SCALE2 = new_inherit(SCALE1) # SCALE3 record class SCALE3 = new_inherit(SCALE1) # MTRIX1 record class # # MTRIXn n=1,2, or 3 MTRIX1 = def_rec([ 8, 10, Pdb_Integer, :serial ], [ 11, 20, Pdb_Real('10.6'), :Mn1 ], [ 21, 30, Pdb_Real('10.6'), :Mn2 ], [ 31, 40, Pdb_Real('10.6'), :Mn3 ], [ 46, 55, Pdb_Real('10.5'), :Vn ], [ 60, 60, Pdb_Integer, :iGiven ] ) # MTRIX2 record class MTRIX2 = new_inherit(MTRIX1) # MTRIX3 record class MTRIX3 = new_inherit(MTRIX1) # TVECT record class TVECT = def_rec([ 8, 10, Pdb_Integer, :serial ], [ 11, 20, Pdb_Real('10.5'), :t1 ], [ 21, 30, Pdb_Real('10.5'), :t2 ], [ 31, 40, Pdb_Real('10.5'), :t3 ], [ 41, 70, Pdb_String, :text ] ) # MODEL record class MODEL = def_rec([ 11, 14, Pdb_Integer, :serial ] ) # ChangeLog: model_serial are changed to serial # ATOM record class ATOM = new_direct([ 7, 11, Pdb_Integer, :serial ], [ 13, 16, Pdb_Atom, :name ], [ 17, 17, Pdb_Character, :altLoc ], [ 18, 20, Pdb_Residue_name, :resName ], [ 22, 22, Pdb_Character, :chainID ], [ 23, 26, Pdb_Integer, :resSeq ], [ 27, 27, Pdb_AChar, :iCode ], [ 31, 38, Pdb_Real('8.3'), :x ], [ 39, 46, Pdb_Real('8.3'), :y ], [ 47, 54, Pdb_Real('8.3'), :z ], [ 55, 60, Pdb_Real('6.2'), :occupancy ], [ 61, 66, Pdb_Real('6.2'), :tempFactor ], [ 73, 76, Pdb_LString(4), :segID ], [ 77, 78, Pdb_LString(2), :element ], [ 79, 80, Pdb_LString(2), :charge ] ) # ATOM record class class ATOM include Utils include Comparable # for backward compatibility alias occ occupancy # for backward compatibility alias bfac tempFactor # residue the atom belongs to. attr_accessor :residue # SIGATM record attr_accessor :sigatm # ANISOU record attr_accessor :anisou # TER record attr_accessor :ter #Returns a Coordinate class instance of the xyz positions def xyz Coordinate[ x, y, z ] end #Returns an array of the xyz positions def to_a [ x, y, z ] end #Sorts based on serial numbers def <=>(other) return serial <=> other.serial end def do_parse return self if @parsed or !@str self.serial = @str[6..10].to_i self.name = @str[12..15].strip self.altLoc = @str[16..16] self.resName = @str[17..19].strip self.chainID = @str[21..21] self.resSeq = @str[22..25].to_i self.iCode = @str[26..26].strip self.x = @str[30..37].to_f self.y = @str[38..45].to_f self.z = @str[46..53].to_f self.occupancy = @str[54..59].to_f self.tempFactor = @str[60..65].to_f self.segID = @str[72..75].to_s.rstrip self.element = @str[76..77].to_s.lstrip self.charge = @str[78..79].to_s.strip @parsed = true self end def justify_atomname atomname = self.name.to_s return atomname[0, 4] if atomname.length >= 4 case atomname.length when 0 return ' ' when 1 return ' ' + atomname + ' ' when 2 if /\A[0-9]/ =~ atomname then return sprintf('%-4s', atomname) elsif /[0-9]\z/ =~ atomname then return sprintf(' %-3s', atomname) end when 3 if /\A[0-9]/ =~ atomname then return sprintf('%-4s', atomname) end end # ambiguous case for two- or three-letter name elem = self.element.to_s.strip if elem.size > 0 and i = atomname.index(elem) then if i == 0 and elem.size == 1 then return sprintf(' %-3s', atomname) else return sprintf('%-4s', atomname) end end if self.class == HETATM then if /\A(B[^AEHIKR]|C[^ADEFLMORSU]|F[^EMR]|H[^EFGOS]|I[^NR]|K[^R]|N[^ABDEIOP]|O[^S]|P[^ABDMORTU]|S[^BCEGIMNR]|V|W|Y[^B])/ =~ atomname then return sprintf(' %-3s', atomname) else return sprintf('%-4s', atomname) end else # ATOM if /\A[CHONS]/ =~ atomname then return sprintf(' %-3s', atomname) else return sprintf('%-4s', atomname) end end # could not be reached here raise 'bug!' end private :justify_atomname def to_s atomname = justify_atomname sprintf("%-6s%5d %-4s%-1s%3s %-1s%4d%-1s %8.3f%8.3f%8.3f%6.2f%6.2f %-4s%2s%-2s\n", self.record_name, self.serial, atomname, self.altLoc, self.resName, self.chainID, self.resSeq, self.iCode, self.x, self.y, self.z, self.occupancy, self.tempFactor, self.segID, self.element, self.charge) end end #class ATOM # SIGATM record class SIGATM = def_rec([ 7, 11, Pdb_Integer, :serial ], [ 13, 16, Pdb_Atom, :name ], [ 17, 17, Pdb_Character, :altLoc ], [ 18, 20, Pdb_Residue_name, :resName ], [ 22, 22, Pdb_Character, :chainID ], [ 23, 26, Pdb_Integer, :resSeq ], [ 27, 27, Pdb_AChar, :iCode ], [ 31, 38, Pdb_Real('8.3'), :sigX ], [ 39, 46, Pdb_Real('8.3'), :sigY ], [ 47, 54, Pdb_Real('8.3'), :sigZ ], [ 55, 60, Pdb_Real('6.2'), :sigOcc ], [ 61, 66, Pdb_Real('6.2'), :sigTemp ], [ 73, 76, Pdb_LString(4), :segID ], [ 77, 78, Pdb_LString(2), :element ], [ 79, 80, Pdb_LString(2), :charge ] ) # ANISOU record class ANISOU = def_rec([ 7, 11, Pdb_Integer, :serial ], [ 13, 16, Pdb_Atom, :name ], [ 17, 17, Pdb_Character, :altLoc ], [ 18, 20, Pdb_Residue_name, :resName ], [ 22, 22, Pdb_Character, :chainID ], [ 23, 26, Pdb_Integer, :resSeq ], [ 27, 27, Pdb_AChar, :iCode ], [ 29, 35, Pdb_Integer, :U11 ], [ 36, 42, Pdb_Integer, :U22 ], [ 43, 49, Pdb_Integer, :U33 ], [ 50, 56, Pdb_Integer, :U12 ], [ 57, 63, Pdb_Integer, :U13 ], [ 64, 70, Pdb_Integer, :U23 ], [ 73, 76, Pdb_LString(4), :segID ], [ 77, 78, Pdb_LString(2), :element ], [ 79, 80, Pdb_LString(2), :charge ] ) # ANISOU record class class ANISOU # SIGUIJ record attr_accessor :siguij end #class ANISOU # SIGUIJ record class SIGUIJ = def_rec([ 7, 11, Pdb_Integer, :serial ], [ 13, 16, Pdb_Atom, :name ], [ 17, 17, Pdb_Character, :altLoc ], [ 18, 20, Pdb_Residue_name, :resName ], [ 22, 22, Pdb_Character, :chainID ], [ 23, 26, Pdb_Integer, :resSeq ], [ 27, 27, Pdb_AChar, :iCode ], [ 29, 35, Pdb_Integer, :SigmaU11 ], [ 36, 42, Pdb_Integer, :SigmaU22 ], [ 43, 49, Pdb_Integer, :SigmaU33 ], [ 50, 56, Pdb_Integer, :SigmaU12 ], [ 57, 63, Pdb_Integer, :SigmaU13 ], [ 64, 70, Pdb_Integer, :SigmaU23 ], [ 73, 76, Pdb_LString(4), :segID ], [ 77, 78, Pdb_LString(2), :element ], [ 79, 80, Pdb_LString(2), :charge ] ) # TER record class TER = def_rec([ 7, 11, Pdb_Integer, :serial ], [ 18, 20, Pdb_Residue_name, :resName ], [ 22, 22, Pdb_Character, :chainID ], [ 23, 26, Pdb_Integer, :resSeq ], [ 27, 27, Pdb_AChar, :iCode ] ) #HETATM = # new_direct([ 7, 11, Pdb_Integer, :serial ], # [ 13, 16, Pdb_Atom, :name ], # [ 17, 17, Pdb_Character, :altLoc ], # [ 18, 20, Pdb_Residue_name, :resName ], # [ 22, 22, Pdb_Character, :chainID ], # [ 23, 26, Pdb_Integer, :resSeq ], # [ 27, 27, Pdb_AChar, :iCode ], # [ 31, 38, Pdb_Real('8.3'), :x ], # [ 39, 46, Pdb_Real('8.3'), :y ], # [ 47, 54, Pdb_Real('8.3'), :z ], # [ 55, 60, Pdb_Real('6.2'), :occupancy ], # [ 61, 66, Pdb_Real('6.2'), :tempFactor ], # [ 73, 76, Pdb_LString(4), :segID ], # [ 77, 78, Pdb_LString(2), :element ], # [ 79, 80, Pdb_LString(2), :charge ] # ) # HETATM record class HETATM = new_inherit(ATOM) # HETATM record class. # It inherits ATOM class. class HETATM; end # ENDMDL record class ENDMDL = def_rec([ 2, 1, Pdb_Integer, :serial ] # dummy field (always 0) ) # CONECT record class CONECT = def_rec([ 7, 11, Pdb_Integer, :serial ], [ 12, 16, Pdb_Integer, :serial ], [ 17, 21, Pdb_Integer, :serial ], [ 22, 26, Pdb_Integer, :serial ], [ 27, 31, Pdb_Integer, :serial ], [ 32, 36, Pdb_Integer, :serial ], [ 37, 41, Pdb_Integer, :serial ], [ 42, 46, Pdb_Integer, :serial ], [ 47, 51, Pdb_Integer, :serial ], [ 52, 56, Pdb_Integer, :serial ], [ 57, 61, Pdb_Integer, :serial ] ) # MASTER record class MASTER = def_rec([ 11, 15, Pdb_Integer, :numRemark ], [ 16, 20, Pdb_Integer, "0" ], [ 21, 25, Pdb_Integer, :numHet ], [ 26, 30, Pdb_Integer, :numHelix ], [ 31, 35, Pdb_Integer, :numSheet ], [ 36, 40, Pdb_Integer, :numTurn ], [ 41, 45, Pdb_Integer, :numSite ], [ 46, 50, Pdb_Integer, :numXform ], [ 51, 55, Pdb_Integer, :numCoord ], [ 56, 60, Pdb_Integer, :numTer ], [ 61, 65, Pdb_Integer, :numConect ], [ 66, 70, Pdb_Integer, :numSeq ] ) # JRNL record classes class Jrnl < self # subrecord of JRNL # 13, 16 # JRNL AUTH record class AUTH = def_rec([ 13, 16, Pdb_String, :sub_record ], # "AUTH" [ 17, 18, Pdb_Continuation, nil ], [ 20, 70, Pdb_List, :authorList ] ) # JRNL TITL record class TITL = def_rec([ 13, 16, Pdb_String, :sub_record ], # "TITL" [ 17, 18, Pdb_Continuation, nil ], [ 20, 70, Pdb_LString, :title ] ) # JRNL EDIT record class EDIT = def_rec([ 13, 16, Pdb_String, :sub_record ], # "EDIT" [ 17, 18, Pdb_Continuation, nil ], [ 20, 70, Pdb_List, :editorList ] ) # JRNL REF record class REF = def_rec([ 13, 16, Pdb_String, :sub_record ], # "REF" [ 17, 18, Pdb_Continuation, nil ], [ 20, 47, Pdb_LString, :pubName ], [ 50, 51, Pdb_LString(2), "V." ], [ 52, 55, Pdb_String, :volume ], [ 57, 61, Pdb_String, :page ], [ 63, 66, Pdb_Integer, :year ] ) # JRNL PUBL record class PUBL = def_rec([ 13, 16, Pdb_String, :sub_record ], # "PUBL" [ 17, 18, Pdb_Continuation, nil ], [ 20, 70, Pdb_LString, :pub ] ) # JRNL REFN record class REFN = def_rec([ 13, 16, Pdb_String, :sub_record ], # "REFN" [ 20, 23, Pdb_LString(4), "ASTM" ], [ 25, 30, Pdb_LString(6), :astm ], [ 33, 34, Pdb_LString(2), :country ], [ 36, 39, Pdb_LString(4), :BorS ], # "ISBN" or "ISSN" [ 41, 65, Pdb_LString, :isbn ], [ 67, 70, Pdb_LString(4), :coden ] # "0353" for unpublished ) # default or unknown record # Default = def_rec([ 13, 16, Pdb_String, :sub_record ]) # "" # definitions (hash) Definition = create_definition_hash end #class JRNL # REMARK record classes for REMARK 1 class Remark1 < self # 13, 16 # REMARK 1 REFERENCE record class EFER = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "1" [ 12, 20, Pdb_String, :sub_record ], # "REFERENCE" [ 22, 70, Pdb_Integer, :refNum ] ) # REMARK 1 AUTH record class AUTH = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "1" [ 13, 16, Pdb_String, :sub_record ], # "AUTH" [ 17, 18, Pdb_Continuation, nil ], [ 20, 70, Pdb_List, :authorList ] ) # REMARK 1 TITL record class TITL = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "1" [ 13, 16, Pdb_String, :sub_record ], # "TITL" [ 17, 18, Pdb_Continuation, nil ], [ 20, 70, Pdb_LString, :title ] ) # REMARK 1 EDIT record class EDIT = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "1" [ 13, 16, Pdb_String, :sub_record ], # "EDIT" [ 17, 18, Pdb_Continuation, nil ], [ 20, 70, Pdb_LString, :editorList ] ) # REMARK 1 REF record class REF = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "1" [ 13, 16, Pdb_LString(3), :sub_record ], # "REF" [ 17, 18, Pdb_Continuation, nil ], [ 20, 47, Pdb_LString, :pubName ], [ 50, 51, Pdb_LString(2), "V." ], [ 52, 55, Pdb_String, :volume ], [ 57, 61, Pdb_String, :page ], [ 63, 66, Pdb_Integer, :year ] ) # REMARK 1 PUBL record class PUBL = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "1" [ 13, 16, Pdb_String, :sub_record ], # "PUBL" [ 17, 18, Pdb_Continuation, nil ], [ 20, 70, Pdb_LString, :pub ] ) # REMARK 1 REFN record class REFN = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "1" [ 13, 16, Pdb_String, :sub_record ], # "REFN" [ 20, 23, Pdb_LString(4), "ASTM" ], [ 25, 30, Pdb_LString, :astm ], [ 33, 34, Pdb_LString, :country ], [ 36, 39, Pdb_LString(4), :BorS ], [ 41, 65, Pdb_LString, :isbn ], [ 68, 70, Pdb_LString(4), :coden ] ) # default (or unknown) record class for REMARK 1 Default = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "1" [ 13, 16, Pdb_String, :sub_record ] # "" ) # definitions (hash) Definition = create_definition_hash end #class Remark1 # REMARK record classes for REMARK 2 class Remark2 < self # 29, 38 == 'ANGSTROMS.' ANGSTROMS = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "2" [ 12, 22, Pdb_LString(11), :sub_record ], # "RESOLUTION." [ 23, 27, Pdb_Real('5.2'), :resolution ], [ 29, 38, Pdb_LString(10), "ANGSTROMS." ] ) # 23, 38 == ' NOT APPLICABLE.' NOT_APPLICABLE = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "2" [ 12, 22, Pdb_LString(11), :sub_record ], # "RESOLUTION." [ 23, 38, Pdb_LString(16), :resolution ], # " NOT APPLICABLE." [ 41, 70, Pdb_String, :comment ] ) # others Default = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], # "2" [ 12, 22, Pdb_LString(11), :sub_record ], # "RESOLUTION." [ 24, 70, Pdb_String, :comment ] ) end #class Remark2 # REMARK record class for REMARK n (n>=3) RemarkN = def_rec([ 8, 10, Pdb_Integer, :remarkNum ], [ 12, 70, Pdb_LString, :text ] ) # default (or unknown) record class Default = def_rec([ 8, 70, Pdb_LString, :text ]) # definitions (hash) Definition = create_definition_hash # END record class. # # Because END is a reserved word of Ruby, it is separately # added to the hash End = def_rec([ 2, 1, Pdb_Integer, :serial ]) # dummy field (always 0) Definition['END'] = End # Basically just look up the class in Definition hash # do some munging for JRNL and REMARK def self.get_record_class(str) t = fetch_record_name(str) if d = Definition[t] then return d end case t when 'JRNL' d = Jrnl::Definition[str[12..15].to_s.strip] when 'REMARK' case str[7..9].to_i when 1 d = Remark1::Definition[str[12..15].to_s.strip] when 2 if str[28..37] == 'ANGSTROMS.' then d = Remark2::ANGSTROMS elsif str[22..37] == ' NOT APPLICABLE.' then d = Remark2::NOT_APPLICABLE else d = Remark2::Default end else d = RemarkN end else # unknown field d = Default end return d end end #class Record Coordinate_fileds = { 'MODEL' => true, 'ENDMDL' => true, 'ATOM' => true, 'HETATM' => true, 'SIGATM' => true, 'SIGUIJ' => true, 'ANISOU' => true, 'TER' => true, } # Creates a new Bio::PDB object from given <em>str</em>. def initialize(str) #Aha! Our entry into the world of PDB parsing, we initialise a PDB #object with the whole PDB file as a string #each PDB has an array of the lines of the original file #a bit memory-tastic! A hash of records and an array of models #also has an id @data = str.split(/[\r\n]+/) @hash = {} @models = [] @id = nil #Flag to say whether the current line is part of a continuation cont = false #Empty current model cModel = Model.new cChain = nil #Chain.new cResidue = nil #Residue.new cLigand = nil #Heterogen.new c_atom = nil #Goes through each line and replace that line with a PDB::Record @data.collect! do |line| #Go to next if the previous line was contiunation able, and #add_continuation returns true. Line is added by add_continuation next if cont and cont = cont.add_continuation(line) #Make the new record f = Record.get_record_class(line).new.initialize_from_string(line) #p f #Set cont cont = f if f.continue? #Set the hash to point to this record either by adding to an #array, or on it's own key = f.record_name if a = @hash[key] then a << f else @hash[key] = [ f ] end # Do something for ATOM and HETATM if key == 'ATOM' or key == 'HETATM' then if cChain and f.chainID == cChain.id chain = cChain else if chain = cModel[f.chainID] cChain = chain unless cChain else # If we don't have chain, add a new chain newChain = Chain.new(f.chainID, cModel) cModel.addChain(newChain) cChain = newChain chain = newChain end end end case key when 'ATOM' c_atom = f residueID = Residue.get_residue_id_from_atom(f) if cResidue and residueID == cResidue.id residue = cResidue else if residue = chain.get_residue_by_id(residueID) cResidue = residue unless cResidue else # add a new residue newResidue = Residue.new(f.resName, f.resSeq, f.iCode, chain) chain.addResidue(newResidue) cResidue = newResidue residue = newResidue end end f.residue = residue residue.addAtom(f) when 'HETATM' c_atom = f residueID = Heterogen.get_residue_id_from_atom(f) if cLigand and residueID == cLigand.id ligand = cLigand else if ligand = chain.get_heterogen_by_id(residueID) cLigand = ligand unless cLigand else # add a new heterogen newLigand = Heterogen.new(f.resName, f.resSeq, f.iCode, chain) chain.addLigand(newLigand) cLigand = newLigand ligand = newLigand #Each model has a special solvent chain. (for compatibility) if f.resName == 'HOH' cModel.addSolvent(newLigand) end end end f.residue = ligand ligand.addAtom(f) when 'MODEL' c_atom = nil if cModel.model_serial or cModel.chains.size > 0 then self.addModel(cModel) end cModel = Model.new(f.serial) when 'TER' if c_atom c_atom.ter = f else #$stderr.puts "Warning: stray TER?" end when 'SIGATM' if c_atom #$stderr.puts "Warning: duplicated SIGATM?" if c_atom.sigatm c_atom.sigatm = f else #$stderr.puts "Warning: stray SIGATM?" end when 'ANISOU' if c_atom #$stderr.puts "Warning: duplicated ANISOU?" if c_atom.anisou c_atom.anisou = f else #$stderr.puts "Warning: stray ANISOU?" end when 'SIGUIJ' if c_atom and c_atom.anisou #$stderr.puts "Warning: duplicated SIGUIJ?" if c_atom.anisou.siguij c_atom.anisou.siguij = f else #$stderr.puts "Warning: stray SIGUIJ?" end else c_atom = nil end f end #each #At the end we need to add the final model self.addModel(cModel) @data.compact! end #def initialize # all records in this entry as an array. attr_reader :data # all records in this entry as an hash accessed by record names. attr_reader :hash # models in this entry (array). attr_reader :models # Adds a <code>Bio::Model</code> object to the current strucutre. # Adds a model to the current structure. # Returns self. def addModel(model) raise "Expecting a Bio::PDB::Model" if not model.is_a? Bio::PDB::Model @models.push(model) self end # Iterates over each model. # Iterates over each of the models in the structure. # Returns <code>self</code>. def each @models.each{ |model| yield model } self end # Alias needed for Bio::PDB::ModelFinder alias each_model each # Provides keyed access to the models based on serial number # returns nil if it's not there def [](key) @models.find{ |model| key == model.model_serial } end #-- # (should it raise an exception?) #++ #-- #Stringifies to a list of atom records - we could add the annotation #as well if needed #++ # Returns a string of Bio::PDB::Models. This propogates down the heirarchy # till you get to Bio::PDB::Record::ATOM which are outputed in PDB format def to_s string = "" @models.each{ |model| string << model.to_s } string << "END\n" return string end #Makes a hash out of an array of PDB::Records and some kind of symbol #.__send__ invokes the method specified by the symbol. #Essentially it ends up with a hash with keys given in the sub_record #Not sure I fully understand this def make_hash(ary, meth) h = {} ary.each do |f| k = f.__send__(meth) h[k] = [] unless h.has_key?(k) h[k] << f end h end private :make_hash #Takes an array and returns another array of PDB::Records def make_grouping(ary, meth) a = [] k_prev = nil ary.each do |f| k = f.__send__(meth) if k_prev and k_prev == k then a.last << f else a << [] a.last << f end k_prev = k end a end private :make_grouping # Gets all records whose record type is _name_. # Returns an array of <code>Bio::PDB::Record::*</code> objects. # # if _name_ is nil, returns hash storing all record data. # # Example: # p pdb.record('HETATM') # p pdb.record['HETATM'] # def record(name = nil) name ? @hash[name] : @hash end #-- # PDB original methods #Returns a hash of the REMARK records based on the remarkNum #++ # Gets REMARK records. # If no arguments, it returns all REMARK records as a hash. # If remark number is specified, returns only corresponding REMARK records. # If number == 1 or 2 ("REMARK 1" or "REMARK 2"), returns an array # of Bio::PDB::Record instances. Otherwise, returns an array of strings. # def remark(nn = nil) unless defined?(@remark) h = make_hash(self.record('REMARK'), :remarkNum) h.each do |i, a| a.shift # remove first record (= space only) if i != 1 and i != 2 then a.collect! { |f| f.text.gsub(/\s+\z/, '') } end end @remark = h end nn ? @remark[nn] : @remark end # Gets JRNL records. # If no arguments, it returns all JRNL records as a hash. # If sub record name is specified, it returns only corresponding records # as an array of Bio::PDB::Record instances. # def jrnl(sub_record = nil) unless defined?(@jrnl) @jrnl = make_hash(self.record('JRNL'), :sub_record) end sub_record ? @jrnl[sub_record] : @jrnl end #-- #Finding methods - just grabs the record with the appropriate id #or returns and array of all of them #++ # Gets HELIX records. # If no arguments are given, it returns all HELIX records. # (Returns an array of <code>Bio::PDB::Record::HELIX</code> instances.) # If <em>helixID</em> is given, it only returns records # corresponding to given <em>helixID</em>. # (Returns an <code>Bio::PDB::Record::HELIX</code> instance.) # def helix(helixID = nil) if helixID then self.record('HELIX').find { |f| f.helixID == helixID } else self.record('HELIX') end end # Gets TURN records. # If no arguments are given, it returns all TURN records. # (Returns an array of <code>Bio::PDB::Record::TURN</code> instances.) # If <em>turnId</em> is given, it only returns a record # corresponding to given <em>turnId</em>. # (Returns an <code>Bio::PDB::Record::TURN</code> instance.) # def turn(turnId = nil) if turnId then self.record('TURN').find { |f| f.turnId == turnId } else self.record('TURN') end end # Gets SHEET records. # If no arguments are given, it returns all SHEET records # as an array of arrays of <code>Bio::PDB::Record::SHEET</code> instances. # If <em>sheetID</em> is given, it returns an array of # <code>Bio::PDB::Record::SHEET</code> instances. def sheet(sheetID = nil) unless defined?(@sheet) @sheet = make_grouping(self.record('SHEET'), :sheetID) end if sheetID then @sheet.find_all { |f| f.first.sheetID == sheetID } else @sheet end end # Gets SSBOND records. def ssbond self.record('SSBOND') end #-- # Get seqres - we get this to return a nice Bio::Seq object #++ # Amino acid or nucleic acid sequence of backbone residues in "SEQRES". # If <em>chainID</em> is given, it returns corresponding sequence # as an array of string. # Otherwise, returns a hash which contains all sequences. # def seqres(chainID = nil) unless defined?(@seqres) h = make_hash(self.record('SEQRES'), :chainID) newHash = {} h.each do |k, a| a.collect! { |f| f.resName } a.flatten! # determine nuc or aa? tmp = Hash.new(0) a[0,13].each { |x| tmp[x.to_s.strip.size] += 1 } if tmp[3] >= tmp[1] then # amino acid sequence a.collect! do |aa| #aa is three letter code: i.e. ALA #need to look up with Ala aa = aa.capitalize (Bio::AminoAcid.three2one(aa) or 'X') end seq = Bio::Sequence::AA.new(a.to_s) else # nucleic acid sequence a.collect! do |na| na = na.strip na.size == 1 ? na : 'n' end seq = Bio::Sequence::NA.new(a.to_s) end newHash[k] = seq end @seqres = newHash end if chainID then @seqres[chainID] else @seqres end end # Gets DBREF records. # Returns an array of Bio::PDB::Record::DBREF objects. # # If <em>chainID</em> is given, it returns corresponding DBREF records. def dbref(chainID = nil) if chainID then self.record('DBREF').find_all { |f| f.chainID == chainID } else self.record('DBREF') end end # Keywords in "KEYWDS". # Returns an array of string. def keywords self.record('KEYWDS').collect { |f| f.keywds }.flatten end # Classification in "HEADER". def classification self.record('HEADER').first.classification end # Get authors in "AUTHOR". def authors self.record('AUTHOR').first.authorList end #-- # Bio::DB methods #++ # PDB identifier written in "HEADER". (e.g. 1A00) def entry_id @id = self.record('HEADER').first.idCode unless @id @id end # Same as <tt>Bio::PDB#entry_id</tt>. def accession self.entry_id end # Title of this entry in "TITLE". def definition self.record('TITLE').first.title end # Current modification number in "REVDAT". def version self.record('REVDAT').first.modNum end end #class PDB end #module Bio
require 'strscan' require 'thread' require 'java' if RUBY_PLATFORM == 'java' module Bio module MAF class ParseError < Exception; end class Header attr_accessor :vars, :alignment_params def initialize(vars, params) @vars = vars @alignment_params = params end def version vars[:version] end def scoring vars[:scoring] end end class Block attr_reader :vars, :sequences, :offset, :size def initialize(*args) @vars, @sequences, @offset, @size = args end def raw_seq(i) sequences.fetch(i) end def each_raw_seq sequences.each { |s| yield s } end def text_size sequences.first.text.size end end class Sequence attr_reader :source, :start, :size, :strand, :src_size, :text attr_accessor :i_data, :quality alias_method :source_size, :src_size def initialize(*args) @source, @start, @size, @strand, @src_size, @text = args end def write_fasta(writer) writer.write("#{source}:#{start}-#{start + size}", text) end end class ChunkReader attr_accessor :chunk_size, :chunk_shift, :pos attr_reader :f def initialize(f, chunk_size) @f = f self.chunk_size = chunk_size @pos = 0 end def chunk_size=(size) check_chunk_size(size) @chunk_size = size # power of 2 so don't worry about rounding @chunk_shift = Math.log2(size).to_i end def check_chunk_size(size) if size < 1 raise "Invalid chunk size: #{size}" end ## test whether it is a power of 2 ## cf. http://bit.ly/JExNc4 if size & (size - 1) != 0 raise "Invalid chunk size (not a power of 2): #{size}}" end end # Reads the next chunk of the file. def read_chunk chunk = f.read(@chunk_size) @pos += chunk.bytesize if chunk return chunk end def read_chunk_at(offset, size_hint=@chunk_size) f.seek(offset) chunk = f.read(size_hint) @pos = offset + chunk.bytesize return chunk end end class ThreadedChunkReader < ChunkReader attr_reader :f def initialize(f, chunk_size, buffer_size=64) super(f, chunk_size) @buffer = SizedQueue.new(buffer_size) @eof_reached = false start_read_ahead end def start_read_ahead @read_thread = Thread.new { read_ahead } end def read_ahead # n = 0 begin f_pos = 0 until f.eof? chunk = f.read(@chunk_size) @buffer << [f_pos, chunk] f_pos += chunk.bytesize # n += 1 # if (n % 100) == 0 # $stderr.puts "buffer size: #{@buffer.size}" # end end @eof_reached = true rescue Exception @read_ahead_ex = $! $stderr.puts "read_ahead aborting: #{$!}" end end def read_chunk raise "readahead failed: #{@read_ahead_ex}" if @read_ahead_ex if @eof_reached && @buffer.empty? return nil else c_pos, chunk = @buffer.shift() @pos = c_pos return chunk end end end module MAFParsing BLOCK_START = /^(?=a)/ BLOCK_START_OR_EOS = /(?:^(?=a))|\z/ EOL_OR_EOF = /\n|\z/ def set_last_block_pos! @last_block_pos = s.string.rindex(BLOCK_START) end def parse_block return nil if at_end if s.pos != last_block_pos # in non-trailing block parse_block_data else # in trailing block fragment parse_trailing_fragment end end ## Read chunks and accumulate a leading fragment until we ## encounter a block start or EOF. def gather_leading_fragment leading_frag = '' while true next_chunk_start = cr.pos next_chunk = read_chunk if next_chunk next_scanner = StringScanner.new(next_chunk) # If this trailing fragment ends with a newline, then an # 'a' at the beginning of the leading fragment is the # start of the next alignment block. if trailing_nl(leading_frag) || trailing_nl(s.string) pat = BLOCK_START else pat = /(?:\n(?=a))/ end frag = next_scanner.scan_until(pat) if frag # got block start leading_frag << frag break else # no block start in this leading_frag << next_chunk end else # EOF @at_end = true break end end return leading_frag, next_scanner, next_chunk_start end def parse_trailing_fragment leading_frag, next_scanner, next_chunk_start = gather_leading_fragment # join fragments and parse trailing_frag = s.rest joined_block = trailing_frag + leading_frag @chunk_start = chunk_start + s.pos @s = StringScanner.new(joined_block) begin block = parse_block_data rescue ParseError => pe parse_error "Could not parse joined fragments: #{pe}\nTRAILING: #{trailing_frag}\nLEADING: #{leading_frag}" end # Set up to parse the next block @s = next_scanner @chunk_start = next_chunk_start unless @at_end set_last_block_pos! end return block end def parse_error(msg) s_start = [s.pos - 10, 0].max s_end = [s.pos + 10, s.string.length].min if s_start > 0 left = s.string[s_start..(s.pos - 1)] else left = '' end right = s.string[s.pos..s_end] extra = "pos #{s.pos} [#{chunk_start + s.pos}], last #{last_block_pos}" raise ParseError, "#{msg} at: '#{left}>><<#{right}' (#{extra})" end S = 's'.getbyte(0) I = 'i'.getbyte(0) E = 'e'.getbyte(0) Q = 'q'.getbyte(0) COMMENT = '#'.getbyte(0) def parse_block_data block_start_pos = s.pos block_offset = chunk_start + block_start_pos s.scan(/^a\s*/) || parse_error("bad a line") block_vars = parse_maf_vars() seqs = [] payload = s.scan_until(/^(?=a)/) unless payload payload = s.rest s.pos = s.string.size # jump to EOS end lines = payload.split("\n") until lines.empty? line = lines.shift first = line.getbyte(0) if first == S seq = parse_seq_line(line) seqs << seq if seq # when 'i' # parts = line.split # parse_error("wrong i source #{src}!") unless seqs.last.source == src # seqs.last.i_data = parts.slice(2..6) # when 'q' # _, src, quality = line.split # parse_error("wrong q source #{src}!") unless seqs.last.source == src # seqs.last.quality = quality elsif [I, E, Q, COMMENT, nil].include? first next else parse_error "unexpected line: '#{line}'" end end return Block.new(block_vars, seqs, block_offset, s.pos - block_start_pos) end def parse_seq_line(line) _, src, start, size, strand, src_size, text = line.split return nil if sequence_filter && ! seq_filter_ok?(src) begin Sequence.new(src, start.to_i, size.to_i, STRAND_SYM.fetch(strand), src_size.to_i, text) rescue KeyError parse_error "invalid sequence line: #{line}" end end def seq_filter_ok?(src) if sequence_filter[:only_species] src_sp = src.split('.', 2)[0] m = sequence_filter[:only_species].find { |sp| src_sp == sp } return m else return true end end def parse_maf_vars vars = {} while s.scan(/(\w+)=(\S*)\s+/) do vars[s[1].to_sym] = s[2] end vars end STRAND_SYM = { '+' => :+, '-' => :- } end class FragmentParseContext include MAFParsing attr_reader :at_end, :s, :last_block_pos, :chunk_start, :parser def initialize(req, parser) @chunk_start = req.offset @block_offsets = req.block_offsets @s = StringScanner.new(req.data) @parser = parser @last_block_pos = -1 @at_end = false end def sequence_filter parser.sequence_filter end def parse_blocks Enumerator.new do |y| @block_offsets.each do |expected_offset| block = parse_block ctx.parse_error("expected a block at offset #{expected_offset} but could not parse one!") unless block ctx.parse_error("got block with offset #{block.offset}, expected #{expected_offset}!") unless block.offset == expected_offset y << block end end end end class FragmentIORequest attr_reader :offset, :length, :block_offsets attr_accessor :data def initialize(offset, length, block_offsets) @offset = offset @length = length @block_offsets = block_offsets end def execute(f) f.seek(offset) @data = f.read(length) end def context(parser) FragmentParseContext.new(self, parser) end end class ParseContext include MAFParsing attr_accessor :f, :s, :cr, :parser attr_accessor :chunk_start, :last_block_pos, :at_end def initialize(fd, chunk_size, parser, opts) @f = fd @parser = parser reader = opts[:chunk_reader] || ChunkReader @cr = reader.new(@f, chunk_size) @last_block_pos = -1 end def sequence_filter parser.sequence_filter end def set_last_block_pos! @last_block_pos = s.string.rindex(BLOCK_START) end def fetch_blocks(offset, len, block_offsets) start_chunk_read_if_needed(offset, len) # read chunks until we have the entire merged set of # blocks ready to parse # to avoid fragment joining append_chunks_to(len) # parse the blocks Enumerator.new do |y| block_offsets.each do |expected_offset| block = parse_block ctx.parse_error("expected a block at offset #{expected_offset} but could not parse one!") unless block ctx.parse_error("got block with offset #{block.offset}, expected #{expected_offset}!") unless block.offset == expected_offset y << block end end end def start_chunk_read_if_needed(offset, len) if chunk_start \ && (chunk_start <= offset) \ && (offset < (chunk_start + s.string.size)) ## the selected offset is in the current chunk s.pos = offset - chunk_start else chunk = cr.read_chunk_at(offset, len) @chunk_start = offset @s = StringScanner.new(chunk) end end def append_chunks_to(len) # XXX: need to rethink this for BGZF; prefetching ChunkReader while s.string.size < len s.string << cr.read_chunk() end end end class Parser include MAFParsing ## Parses alignment blocks by reading a chunk of the file at a time. attr_reader :header, :file_spec, :f, :s, :cr, :at_end attr_reader :chunk_start, :last_block_pos attr_accessor :sequence_filter SEQ_CHUNK_SIZE = 131072 RANDOM_CHUNK_SIZE = 4096 MERGE_MAX = SEQ_CHUNK_SIZE def initialize(file_spec, opts={}) @opts = opts chunk_size = opts[:chunk_size] || SEQ_CHUNK_SIZE @random_access_chunk_size = opts[:random_chunk_size] || RANDOM_CHUNK_SIZE @merge_max = opts[:merge_max] || MERGE_MAX @chunk_start = 0 @file_spec = file_spec @f = File.open(file_spec) reader = opts[:chunk_reader] || ChunkReader @cr = reader.new(@f, chunk_size) @s = StringScanner.new(read_chunk()) set_last_block_pos! @at_end = false _parse_header() end def context(chunk_size) # IO#dup calls dup(2) internally, but seems broken on JRuby... fd = File.open(file_spec) ParseContext.new(fd, chunk_size, self, @opts) end def with_context(chunk_size) ctx = context(chunk_size) begin yield ctx ensure ctx.f.close end end def read_chunk cr.read_chunk end def fetch_blocks(fetch_list, filters=nil) ## fetch_list: array of [offset, length, block_count] tuples ## returns array of Blocks merged = merge_fetch_list(fetch_list) if RUBY_PLATFORM == 'java' && @opts.fetch(:threads, 1) > 1 #fetch_blocks_merged_parallel(merged) #fetch_blocks_merged_parallel2(merged) fetch_blocks_merged_parallel3(merged) else fetch_blocks_merged(merged) end end def fetch_blocks_merged(fetch_list) Enumerator.new do |y| start = Time.now total_size = fetch_list.collect { |e| e[1] }.reduce(:+) with_context(@random_access_chunk_size) do |ctx| fetch_list.each do |e| ctx.fetch_blocks(*e).each do |block| y << block #total_size += block.size end end end elapsed = Time.now - start rate = (total_size / 1048576.0) / elapsed $stderr.printf("Fetched blocks in %.3fs, %.1f MB/s.\n", elapsed, rate) end end def fetch_blocks_merged_parallel2(fetch_list) Enumerator.new do |y| queue = java.util.concurrent.LinkedBlockingQueue.new(32) ctl = ParallelIO::Controller.new(file_spec) ctl.min_io = 3 fetch_list.each do |entry| ctl.read_queue.add FragmentIORequest.new(*entry) end ctl.on_data do |data| ctx = data.context(self) ctx.parse_blocks.each do |block| queue.put(block) end end ctl.start start = Time.now total_size = 0 $stderr.puts "starting parallel I/O" dumper = Thread.new do begin while ctl.workers.find { |w| w.thread.alive? } ctl.dump_state sleep(0.1) end rescue $stderr.puts "#{$!.class}: #{$!}" $stderr.puts $!.backtrace.join("\n") end end while true block = queue.poll(30, java.util.concurrent.TimeUnit::MILLISECONDS) if block y << block total_size += block.size elsif ctl.finished? $stderr.puts "finished, shutting down parallel I/O" elapsed = Time.now - start rate = (total_size / 1048576.0) / elapsed $stderr.printf("Fetched blocks in %.3fs, %.1f MB/s.", elapsed, rate) v ctl.shutdown break end end end end def fetch_blocks_merged_parallel3(fetch_list) io_parallelism = 3 n_cpu = 3 total_size = fetch_list.collect { |e| e[1] }.reduce(:+) jobs_q = java.util.concurrent.ConcurrentLinkedQueue.new() data_q = java.util.concurrent.LinkedBlockingQueue.new(128) yield_q = java.util.concurrent.LinkedBlockingQueue.new(128) fetch_list.each do |entry| jobs_q.add FragmentIORequest.new(*entry) end Enumerator.new do |y| io_threads = [] parse_threads = [] start = Time.now io_parallelism.times { io_threads << make_io_worker(file_spec, jobs_q, data_q) } n_cpu.times { parse_threads << make_parse_worker(data_q, yield_q) } io_parallelism.times { jobs_q.add(:stop) } n_completed = 0 while n_completed < fetch_list.size blocks = yield_q.take blocks.each do |block| y << block end n_completed += 1 end n_cpu.times { data_q.put(:stop) } elapsed = Time.now - start $stderr.printf("Fetched blocks in %.1fs.\n", elapsed) mb = total_size / 1048576.0 $stderr.printf("%.3f MB processed (%.1f MB/s).\n", mb, mb / elapsed) end end def make_io_worker(path, jobs, completed) Thread.new do begin fd = File.open(path) begin while true req = jobs.poll break if req == :stop req.execute(fd) completed.put(req) end ensure fd.close end rescue Exception => e $stderr.puts "Worker failing: #{e.class}: #{e}" $stderr.puts e.backtrace.join("\n") raise e end end end def make_parse_worker(jobs, completed) Thread.new do begin while true do data = jobs.take break if data == :stop ctx = data.context(self) completed.put(ctx.parse_blocks.to_a) end rescue Exception => e $stderr.puts "Worker failing: #{e.class}: #{e}" $stderr.puts e.backtrace.join("\n") raise e end end end def fetch_blocks_merged_parallel(fetch_list) Enumerator.new do |y| total_size = fetch_list.collect { |e| e[1] }.reduce(:+) start = Time.now n_threads = @opts.fetch(:threads, 1) # TODO: break entries up into longer runs for more # sequential I/O jobs = java.util.concurrent.ConcurrentLinkedQueue.new(fetch_list) completed = java.util.concurrent.ArrayBlockingQueue.new(128) threads = [] n_threads.times { threads << make_worker(jobs, completed) } n_completed = 0 while (n_completed < fetch_list.size) \ && threads.find { |t| t.alive? } c = completed.take raise "worker failed: #{c}" if c.is_a? Exception c.each do |block| y << block #bytes += block.size end n_completed += 1 end if n_completed < fetch_list.size raise "No threads alive, completed #{n_completed}/#{jobs.size} jobs!" end elapsed = Time.now - start $stderr.printf("Fetched blocks from %d threads in %.3fs.\n", n_threads, elapsed) mb = total_size / 1048576.0 $stderr.printf("%.3f MB processed (%.3f MB/s).\n", mb, mb / elapsed) end end def make_worker(jobs, completed) Thread.new do with_context(@random_access_chunk_size) do |ctx| total_size = 0 n = 0 while true req = jobs.poll break unless req begin n_blocks = req[2].size blocks = ctx.fetch_blocks(*req).to_a if blocks.size != n_blocks raise "expected #{n_blocks}, got #{blocks.size}: #{e.inspect}" end completed.put(blocks) total_size += req[1] n += 1 rescue Exception => e completed.put(e) $stderr.puts "Worker failing: #{e.class}: #{e}" $stderr.puts e.backtrace.join("\n") raise e end end end end end def worker_fetch_blocks(*args) with_context(@random_access_chunk_size) do |ctx| ctx.fetch_blocks(*args).to_a end end def merge_fetch_list(orig_fl) fl = orig_fl.dup r = [] until fl.empty? do cur = fl.shift if r.last \ && (r.last[0] + r.last[1]) == cur[0] \ && (r.last[1] + cur[1]) <= @merge_max # contiguous with the previous one # add to length and increment count r.last[1] += cur[1] r.last[2] << cur[0] else cur << [cur[0]] r << cur end end return r end def _parse_header parse_error("not a MAF file") unless s.scan(/##maf\s*/) vars = parse_maf_vars() align_params = nil while s.scan(/^#\s*(.+?)\n/) if align_params == nil align_params = s[1] else align_params << ' ' << s[1] end end @header = Header.new(vars, align_params) s.skip_until BLOCK_START || parse_error("Cannot find block start!") end ## On finding the start of a block: ## See whether we are at the last block in the chunk. ## If at the last block: ## If at EOF: last block. ## If not: ## Read the next chunk ## Find the start of the next block in that chunk ## Concatenate the two block fragments ## Parse the resulting block ## Promote the next scanner, positioned def trailing_nl(string) if string.empty? false else s.string[s.string.size - 1] == "\n" end end def each_block until at_end yield parse_block() end end end end end Use LinkedBlockingQueue, improve output. require 'strscan' require 'thread' require 'java' if RUBY_PLATFORM == 'java' module Bio module MAF class ParseError < Exception; end class Header attr_accessor :vars, :alignment_params def initialize(vars, params) @vars = vars @alignment_params = params end def version vars[:version] end def scoring vars[:scoring] end end class Block attr_reader :vars, :sequences, :offset, :size def initialize(*args) @vars, @sequences, @offset, @size = args end def raw_seq(i) sequences.fetch(i) end def each_raw_seq sequences.each { |s| yield s } end def text_size sequences.first.text.size end end class Sequence attr_reader :source, :start, :size, :strand, :src_size, :text attr_accessor :i_data, :quality alias_method :source_size, :src_size def initialize(*args) @source, @start, @size, @strand, @src_size, @text = args end def write_fasta(writer) writer.write("#{source}:#{start}-#{start + size}", text) end end class ChunkReader attr_accessor :chunk_size, :chunk_shift, :pos attr_reader :f def initialize(f, chunk_size) @f = f self.chunk_size = chunk_size @pos = 0 end def chunk_size=(size) check_chunk_size(size) @chunk_size = size # power of 2 so don't worry about rounding @chunk_shift = Math.log2(size).to_i end def check_chunk_size(size) if size < 1 raise "Invalid chunk size: #{size}" end ## test whether it is a power of 2 ## cf. http://bit.ly/JExNc4 if size & (size - 1) != 0 raise "Invalid chunk size (not a power of 2): #{size}}" end end # Reads the next chunk of the file. def read_chunk chunk = f.read(@chunk_size) @pos += chunk.bytesize if chunk return chunk end def read_chunk_at(offset, size_hint=@chunk_size) f.seek(offset) chunk = f.read(size_hint) @pos = offset + chunk.bytesize return chunk end end class ThreadedChunkReader < ChunkReader attr_reader :f def initialize(f, chunk_size, buffer_size=64) super(f, chunk_size) @buffer = SizedQueue.new(buffer_size) @eof_reached = false start_read_ahead end def start_read_ahead @read_thread = Thread.new { read_ahead } end def read_ahead # n = 0 begin f_pos = 0 until f.eof? chunk = f.read(@chunk_size) @buffer << [f_pos, chunk] f_pos += chunk.bytesize # n += 1 # if (n % 100) == 0 # $stderr.puts "buffer size: #{@buffer.size}" # end end @eof_reached = true rescue Exception @read_ahead_ex = $! $stderr.puts "read_ahead aborting: #{$!}" end end def read_chunk raise "readahead failed: #{@read_ahead_ex}" if @read_ahead_ex if @eof_reached && @buffer.empty? return nil else c_pos, chunk = @buffer.shift() @pos = c_pos return chunk end end end module MAFParsing BLOCK_START = /^(?=a)/ BLOCK_START_OR_EOS = /(?:^(?=a))|\z/ EOL_OR_EOF = /\n|\z/ def set_last_block_pos! @last_block_pos = s.string.rindex(BLOCK_START) end def parse_block return nil if at_end if s.pos != last_block_pos # in non-trailing block parse_block_data else # in trailing block fragment parse_trailing_fragment end end ## Read chunks and accumulate a leading fragment until we ## encounter a block start or EOF. def gather_leading_fragment leading_frag = '' while true next_chunk_start = cr.pos next_chunk = read_chunk if next_chunk next_scanner = StringScanner.new(next_chunk) # If this trailing fragment ends with a newline, then an # 'a' at the beginning of the leading fragment is the # start of the next alignment block. if trailing_nl(leading_frag) || trailing_nl(s.string) pat = BLOCK_START else pat = /(?:\n(?=a))/ end frag = next_scanner.scan_until(pat) if frag # got block start leading_frag << frag break else # no block start in this leading_frag << next_chunk end else # EOF @at_end = true break end end return leading_frag, next_scanner, next_chunk_start end def parse_trailing_fragment leading_frag, next_scanner, next_chunk_start = gather_leading_fragment # join fragments and parse trailing_frag = s.rest joined_block = trailing_frag + leading_frag @chunk_start = chunk_start + s.pos @s = StringScanner.new(joined_block) begin block = parse_block_data rescue ParseError => pe parse_error "Could not parse joined fragments: #{pe}\nTRAILING: #{trailing_frag}\nLEADING: #{leading_frag}" end # Set up to parse the next block @s = next_scanner @chunk_start = next_chunk_start unless @at_end set_last_block_pos! end return block end def parse_error(msg) s_start = [s.pos - 10, 0].max s_end = [s.pos + 10, s.string.length].min if s_start > 0 left = s.string[s_start..(s.pos - 1)] else left = '' end right = s.string[s.pos..s_end] extra = "pos #{s.pos} [#{chunk_start + s.pos}], last #{last_block_pos}" raise ParseError, "#{msg} at: '#{left}>><<#{right}' (#{extra})" end S = 's'.getbyte(0) I = 'i'.getbyte(0) E = 'e'.getbyte(0) Q = 'q'.getbyte(0) COMMENT = '#'.getbyte(0) def parse_block_data block_start_pos = s.pos block_offset = chunk_start + block_start_pos s.scan(/^a\s*/) || parse_error("bad a line") block_vars = parse_maf_vars() seqs = [] payload = s.scan_until(/^(?=a)/) unless payload payload = s.rest s.pos = s.string.size # jump to EOS end lines = payload.split("\n") until lines.empty? line = lines.shift first = line.getbyte(0) if first == S seq = parse_seq_line(line) seqs << seq if seq # when 'i' # parts = line.split # parse_error("wrong i source #{src}!") unless seqs.last.source == src # seqs.last.i_data = parts.slice(2..6) # when 'q' # _, src, quality = line.split # parse_error("wrong q source #{src}!") unless seqs.last.source == src # seqs.last.quality = quality elsif [I, E, Q, COMMENT, nil].include? first next else parse_error "unexpected line: '#{line}'" end end return Block.new(block_vars, seqs, block_offset, s.pos - block_start_pos) end def parse_seq_line(line) _, src, start, size, strand, src_size, text = line.split return nil if sequence_filter && ! seq_filter_ok?(src) begin Sequence.new(src, start.to_i, size.to_i, STRAND_SYM.fetch(strand), src_size.to_i, text) rescue KeyError parse_error "invalid sequence line: #{line}" end end def seq_filter_ok?(src) if sequence_filter[:only_species] src_sp = src.split('.', 2)[0] m = sequence_filter[:only_species].find { |sp| src_sp == sp } return m else return true end end def parse_maf_vars vars = {} while s.scan(/(\w+)=(\S*)\s+/) do vars[s[1].to_sym] = s[2] end vars end STRAND_SYM = { '+' => :+, '-' => :- } end class FragmentParseContext include MAFParsing attr_reader :at_end, :s, :last_block_pos, :chunk_start, :parser def initialize(req, parser) @chunk_start = req.offset @block_offsets = req.block_offsets @s = StringScanner.new(req.data) @parser = parser @last_block_pos = -1 @at_end = false end def sequence_filter parser.sequence_filter end def parse_blocks Enumerator.new do |y| @block_offsets.each do |expected_offset| block = parse_block ctx.parse_error("expected a block at offset #{expected_offset} but could not parse one!") unless block ctx.parse_error("got block with offset #{block.offset}, expected #{expected_offset}!") unless block.offset == expected_offset y << block end end end end class FragmentIORequest attr_reader :offset, :length, :block_offsets attr_accessor :data def initialize(offset, length, block_offsets) @offset = offset @length = length @block_offsets = block_offsets end def execute(f) f.seek(offset) @data = f.read(length) end def context(parser) FragmentParseContext.new(self, parser) end end class ParseContext include MAFParsing attr_accessor :f, :s, :cr, :parser attr_accessor :chunk_start, :last_block_pos, :at_end def initialize(fd, chunk_size, parser, opts) @f = fd @parser = parser reader = opts[:chunk_reader] || ChunkReader @cr = reader.new(@f, chunk_size) @last_block_pos = -1 end def sequence_filter parser.sequence_filter end def set_last_block_pos! @last_block_pos = s.string.rindex(BLOCK_START) end def fetch_blocks(offset, len, block_offsets) start_chunk_read_if_needed(offset, len) # read chunks until we have the entire merged set of # blocks ready to parse # to avoid fragment joining append_chunks_to(len) # parse the blocks Enumerator.new do |y| block_offsets.each do |expected_offset| block = parse_block ctx.parse_error("expected a block at offset #{expected_offset} but could not parse one!") unless block ctx.parse_error("got block with offset #{block.offset}, expected #{expected_offset}!") unless block.offset == expected_offset y << block end end end def start_chunk_read_if_needed(offset, len) if chunk_start \ && (chunk_start <= offset) \ && (offset < (chunk_start + s.string.size)) ## the selected offset is in the current chunk s.pos = offset - chunk_start else chunk = cr.read_chunk_at(offset, len) @chunk_start = offset @s = StringScanner.new(chunk) end end def append_chunks_to(len) # XXX: need to rethink this for BGZF; prefetching ChunkReader while s.string.size < len s.string << cr.read_chunk() end end end class Parser include MAFParsing ## Parses alignment blocks by reading a chunk of the file at a time. attr_reader :header, :file_spec, :f, :s, :cr, :at_end attr_reader :chunk_start, :last_block_pos attr_accessor :sequence_filter SEQ_CHUNK_SIZE = 131072 RANDOM_CHUNK_SIZE = 4096 MERGE_MAX = SEQ_CHUNK_SIZE def initialize(file_spec, opts={}) @opts = opts chunk_size = opts[:chunk_size] || SEQ_CHUNK_SIZE @random_access_chunk_size = opts[:random_chunk_size] || RANDOM_CHUNK_SIZE @merge_max = opts[:merge_max] || MERGE_MAX @chunk_start = 0 @file_spec = file_spec @f = File.open(file_spec) reader = opts[:chunk_reader] || ChunkReader @cr = reader.new(@f, chunk_size) @s = StringScanner.new(read_chunk()) set_last_block_pos! @at_end = false _parse_header() end def context(chunk_size) # IO#dup calls dup(2) internally, but seems broken on JRuby... fd = File.open(file_spec) ParseContext.new(fd, chunk_size, self, @opts) end def with_context(chunk_size) ctx = context(chunk_size) begin yield ctx ensure ctx.f.close end end def read_chunk cr.read_chunk end def fetch_blocks(fetch_list, filters=nil) ## fetch_list: array of [offset, length, block_count] tuples ## returns array of Blocks merged = merge_fetch_list(fetch_list) if RUBY_PLATFORM == 'java' && @opts.fetch(:threads, 1) > 1 #fetch_blocks_merged_parallel(merged) #fetch_blocks_merged_parallel2(merged) fetch_blocks_merged_parallel3(merged) else fetch_blocks_merged(merged) end end def fetch_blocks_merged(fetch_list) Enumerator.new do |y| start = Time.now total_size = fetch_list.collect { |e| e[1] }.reduce(:+) with_context(@random_access_chunk_size) do |ctx| fetch_list.each do |e| ctx.fetch_blocks(*e).each do |block| y << block #total_size += block.size end end end elapsed = Time.now - start rate = (total_size / 1048576.0) / elapsed $stderr.printf("Fetched blocks in %.3fs, %.1f MB/s.\n", elapsed, rate) end end def fetch_blocks_merged_parallel2(fetch_list) Enumerator.new do |y| queue = java.util.concurrent.LinkedBlockingQueue.new(32) ctl = ParallelIO::Controller.new(file_spec) ctl.min_io = 3 fetch_list.each do |entry| ctl.read_queue.add FragmentIORequest.new(*entry) end ctl.on_data do |data| ctx = data.context(self) ctx.parse_blocks.each do |block| queue.put(block) end end ctl.start start = Time.now total_size = 0 $stderr.puts "starting parallel I/O" dumper = Thread.new do begin while ctl.workers.find { |w| w.thread.alive? } ctl.dump_state sleep(0.1) end rescue $stderr.puts "#{$!.class}: #{$!}" $stderr.puts $!.backtrace.join("\n") end end while true block = queue.poll(30, java.util.concurrent.TimeUnit::MILLISECONDS) if block y << block total_size += block.size elsif ctl.finished? $stderr.puts "finished, shutting down parallel I/O" elapsed = Time.now - start rate = (total_size / 1048576.0) / elapsed $stderr.printf("Fetched blocks in %.3fs, %.1f MB/s.", elapsed, rate) v ctl.shutdown break end end end end def fetch_blocks_merged_parallel3(fetch_list) io_parallelism = 3 n_cpu = 3 total_size = fetch_list.collect { |e| e[1] }.reduce(:+) jobs_q = java.util.concurrent.ConcurrentLinkedQueue.new() data_q = java.util.concurrent.LinkedBlockingQueue.new(128) yield_q = java.util.concurrent.LinkedBlockingQueue.new(128) fetch_list.each do |entry| jobs_q.add FragmentIORequest.new(*entry) end Enumerator.new do |y| io_threads = [] parse_threads = [] start = Time.now io_parallelism.times { io_threads << make_io_worker(file_spec, jobs_q, data_q) } n_cpu.times { parse_threads << make_parse_worker(data_q, yield_q) } io_parallelism.times { jobs_q.add(:stop) } n_completed = 0 while n_completed < fetch_list.size blocks = yield_q.take blocks.each do |block| y << block end n_completed += 1 end n_cpu.times { data_q.put(:stop) } elapsed = Time.now - start $stderr.printf("Fetched blocks in %.1fs.\n", elapsed) mb = total_size / 1048576.0 $stderr.printf("%.3f MB processed (%.1f MB/s).\n", mb, mb / elapsed) end end def make_io_worker(path, jobs, completed) Thread.new do begin fd = File.open(path) begin while true req = jobs.poll break if req == :stop req.execute(fd) completed.put(req) end ensure fd.close end rescue Exception => e $stderr.puts "Worker failing: #{e.class}: #{e}" $stderr.puts e.backtrace.join("\n") raise e end end end def make_parse_worker(jobs, completed) Thread.new do begin while true do data = jobs.take break if data == :stop ctx = data.context(self) completed.put(ctx.parse_blocks.to_a) end rescue Exception => e $stderr.puts "Worker failing: #{e.class}: #{e}" $stderr.puts e.backtrace.join("\n") raise e end end end def fetch_blocks_merged_parallel(fetch_list) Enumerator.new do |y| total_size = fetch_list.collect { |e| e[1] }.reduce(:+) start = Time.now n_threads = @opts.fetch(:threads, 1) # TODO: break entries up into longer runs for more # sequential I/O jobs = java.util.concurrent.ConcurrentLinkedQueue.new(fetch_list) completed = java.util.concurrent.LinkedBlockingQueue.new(128) threads = [] n_threads.times { threads << make_worker(jobs, completed) } n_completed = 0 while (n_completed < fetch_list.size) \ && threads.find { |t| t.alive? } c = completed.take raise "worker failed: #{c}" if c.is_a? Exception c.each do |block| y << block end n_completed += 1 end if n_completed < fetch_list.size raise "No threads alive, completed #{n_completed}/#{jobs.size} jobs!" end elapsed = Time.now - start $stderr.printf("Fetched blocks from %d threads in %.1fs.\n", n_threads, elapsed) mb = total_size / 1048576.0 $stderr.printf("%.3f MB processed (%.1f MB/s).\n", mb, mb / elapsed) end end def make_worker(jobs, completed) Thread.new do with_context(@random_access_chunk_size) do |ctx| total_size = 0 n = 0 while true req = jobs.poll break unless req begin n_blocks = req[2].size blocks = ctx.fetch_blocks(*req).to_a if blocks.size != n_blocks raise "expected #{n_blocks}, got #{blocks.size}: #{e.inspect}" end completed.put(blocks) total_size += req[1] n += 1 rescue Exception => e completed.put(e) $stderr.puts "Worker failing: #{e.class}: #{e}" $stderr.puts e.backtrace.join("\n") raise e end end end end end def worker_fetch_blocks(*args) with_context(@random_access_chunk_size) do |ctx| ctx.fetch_blocks(*args).to_a end end def merge_fetch_list(orig_fl) fl = orig_fl.dup r = [] until fl.empty? do cur = fl.shift if r.last \ && (r.last[0] + r.last[1]) == cur[0] \ && (r.last[1] + cur[1]) <= @merge_max # contiguous with the previous one # add to length and increment count r.last[1] += cur[1] r.last[2] << cur[0] else cur << [cur[0]] r << cur end end return r end def _parse_header parse_error("not a MAF file") unless s.scan(/##maf\s*/) vars = parse_maf_vars() align_params = nil while s.scan(/^#\s*(.+?)\n/) if align_params == nil align_params = s[1] else align_params << ' ' << s[1] end end @header = Header.new(vars, align_params) s.skip_until BLOCK_START || parse_error("Cannot find block start!") end ## On finding the start of a block: ## See whether we are at the last block in the chunk. ## If at the last block: ## If at EOF: last block. ## If not: ## Read the next chunk ## Find the start of the next block in that chunk ## Concatenate the two block fragments ## Parse the resulting block ## Promote the next scanner, positioned def trailing_nl(string) if string.empty? false else s.string[s.string.size - 1] == "\n" end end def each_block until at_end yield parse_block() end end end end end
module Blizzardry class MPQ require 'blizzardry/mpq/file' require 'blizzardry/mpq/storm' def initialize(handle) @handle = handle end def patch(archive) Storm.SFileOpenPatchArchive(@handle, archive, nil, 0) end def patched? Storm.SFileIsPatchedArchive(@handle) end def close Storm.SFileCloseArchive(@handle) end def has?(filename) Storm.SFileHasFile(@handle, filename) end def find(query) results = [] result = Storm::SearchResult.new handle = Storm.SFileFindFirstFile(@handle, query, result, nil) unless handle.null? results << result[:filename].to_s yield results.last if block_given? while Storm.SFileFindNextFile(handle, result) results << result[:filename].to_s yield results.last if block_given? end end results ensure Storm.SFileFindClose(handle) end def get(filename) handle = FFI::MemoryPointer.new :pointer if Storm.SFileOpenFileEx(@handle, filename, 0, handle) File.new(handle.read_pointer) end end def extract(filename, local) Storm.SFileExtractFile(@handle, filename, local, 0) end class << self private :new def open(archive, flags = 0) handle = FFI::MemoryPointer.new :pointer return unless Storm.SFileOpenArchive(archive, 0, flags, handle) mpq = new(handle.read_pointer) if block_given? yield mpq mpq.close nil else mpq end end end end end Support specifying patch prefix module Blizzardry class MPQ require 'blizzardry/mpq/file' require 'blizzardry/mpq/storm' def initialize(handle) @handle = handle end def patch(archive, prefix = nil) Storm.SFileOpenPatchArchive(@handle, archive, prefix, 0) end def patched? Storm.SFileIsPatchedArchive(@handle) end def close Storm.SFileCloseArchive(@handle) end def has?(filename) Storm.SFileHasFile(@handle, filename) end def find(query) results = [] result = Storm::SearchResult.new handle = Storm.SFileFindFirstFile(@handle, query, result, nil) unless handle.null? results << result[:filename].to_s yield results.last if block_given? while Storm.SFileFindNextFile(handle, result) results << result[:filename].to_s yield results.last if block_given? end end results ensure Storm.SFileFindClose(handle) end def get(filename) handle = FFI::MemoryPointer.new :pointer if Storm.SFileOpenFileEx(@handle, filename, 0, handle) File.new(handle.read_pointer) end end def extract(filename, local) Storm.SFileExtractFile(@handle, filename, local, 0) end class << self private :new def open(archive, flags = 0) handle = FFI::MemoryPointer.new :pointer return unless Storm.SFileOpenArchive(archive, 0, flags, handle) mpq = new(handle.read_pointer) if block_given? yield mpq mpq.close nil else mpq end end end end end
require 'active_support/concern' module Burlesque module Role extend ActiveSupport::Concern included do # has_many :role_groups # has_many :groups, through: :role_groups, dependent: :destroy # has_many :authorizations, dependent: :destroy # # for has_many :admins relations see admins function # attr_accessible :name # validates :name, presence: true, uniqueness: true scope :action, lambda { |action| where('name LIKE ?', "#{action}_%") } scope :not_action, lambda { |action| where('name NOT LIKE ?', "#{action}_%") } scope :resource, lambda { |model| where('name LIKE ? or name LIKE ?', "%_#{model.to_s.singularize}", "%_#{model.to_s.pluralize}") } scope :not_resource, lambda { |model| where('name NOT LIKE ? AND name NOT LIKE ?', "%_#{model.to_s.singularize}", "%_#{model.to_s.pluralize}") } end # module InstanceMethods # def admins # authorizations.map &:authorizable # end # # Public: Traduce el nombre de un rol. # # # # Returns el nombre del rol ya traducido. # def translate_name # translate = I18n.t(name.to_sym, scope: :authorizations) # return translate unless translate.include?('translation missing:') # action = name.split('_', 2).first # model = name.split('_', 2).last # count = model == model.pluralize ? 2 : 1 # model = model.pluralize # translate = I18n.t(action.to_sym, scope: :authorizations) + ' ' + model.classify.constantize.model_name.human(count: count) # end module ClassMethods def for model if model.class == String resource = model.classify.constantize.model_name.underscore elsif model.class == Symbol resource = model.to_s.classify.constantize.model_name.underscore elsif model.class == Class resource = model.model_name.underscore end if resource Role.create(name: "read_#{resource.pluralize}") unless Role.where(name: "read_#{resource.pluralize}").any? Role.create(name: "show_#{resource}") unless Role.where(name: "show_#{resource}").any? Role.create(name: "create_#{resource}") unless Role.where(name: "create_#{resource}").any? Role.create(name: "update_#{resource}") unless Role.where(name: "update_#{resource}").any? Role.create(name: "destroy_#{resource}") unless Role.where(name: "destroy_#{resource}").any? else raise I18n.t('errors.messages.invalid_param', param: model.class) end end end end end fix class method function where in module require 'active_support/concern' module Burlesque module Role extend ActiveSupport::Concern included do # has_many :role_groups # has_many :groups, through: :role_groups, dependent: :destroy # has_many :authorizations, dependent: :destroy # # for has_many :admins relations see admins function # attr_accessible :name # validates :name, presence: true, uniqueness: true scope :action, lambda { |action| where('name LIKE ?', "#{action}_%") } scope :not_action, lambda { |action| where('name NOT LIKE ?', "#{action}_%") } scope :resource, lambda { |model| where('name LIKE ? or name LIKE ?', "%_#{model.to_s.singularize}", "%_#{model.to_s.pluralize}") } scope :not_resource, lambda { |model| where('name NOT LIKE ? AND name NOT LIKE ?', "%_#{model.to_s.singularize}", "%_#{model.to_s.pluralize}") } end # module InstanceMethods # def admins # authorizations.map &:authorizable # end # # Public: Traduce el nombre de un rol. # # # # Returns el nombre del rol ya traducido. # def translate_name # translate = I18n.t(name.to_sym, scope: :authorizations) # return translate unless translate.include?('translation missing:') # action = name.split('_', 2).first # model = name.split('_', 2).last # count = model == model.pluralize ? 2 : 1 # model = model.pluralize # translate = I18n.t(action.to_sym, scope: :authorizations) + ' ' + model.classify.constantize.model_name.human(count: count) # end module ClassMethods def for model if model.class == String resource = model.classify.constantize.model_name.underscore elsif model.class == Symbol resource = model.to_s.classify.constantize.model_name.underscore elsif model.class == Class resource = model.model_name.underscore end if resource self.create(name: "read_#{resource.pluralize}") unless self.where(name: "read_#{resource.pluralize}").any? self.create(name: "show_#{resource}") unless self.where(name: "show_#{resource}").any? self.create(name: "create_#{resource}") unless self.where(name: "create_#{resource}").any? self.create(name: "update_#{resource}") unless self.where(name: "update_#{resource}").any? self.create(name: "destroy_#{resource}") unless self.where(name: "destroy_#{resource}").any? else raise I18n.t('errors.messages.invalid_param', param: model.class) end end end end end
module Casbah VERSION = '0.0.1' end Resets the version to 0.0.1.pre.1 module Casbah VERSION = '0.0.1.pre.1' end
# Monkey patch the original require 'xml_parser' class GeneratorHelper # The only change to the original is the replaced regex match def test_results_error_handler(executable, shell_result) if (shell_result[:output].nil? or shell_result[:output].strip.empty?) error = true # mirror style of generic tool_executor failure output notice = "\n" + "ERROR: Test executable \"#{File.basename(executable)}\" failed.\n" + "> Produced no output to $stdout.\n" # elsif ((shell_result[:output] =~ CATCH_XML_STATISTICS_PATTERN).nil?) # error = true # # mirror style of generic tool_executor failure output # notice = "\n" + # "ERROR: Test executable \"#{File.basename(executable)}\" failed.\n" + # "> Produced no final test result counts in $stdout:\n" + # "#{shell_result[:output].strip}\n" end if (error) # since we told the tool executor to ignore the exit code, handle it explicitly here notice += "> And exited with status: [#{shell_result[:exit_code]}] (count of failed tests).\n" if (shell_result[:exit_code] != nil) notice += "> And then likely crashed.\n" if (shell_result[:exit_code] == nil) notice += "> This is often a symptom of a bad memory access in source or test code.\n\n" @streaminator.stderr_puts(notice, Verbosity::COMPLAIN) raise end end end # Monkey patch the original class GeneratorTestResults def process_and_write_results(unity_shell_result, results_file, test_file) output_file = results_file xml_output = unity_shell_result[:output] catch_xml = Catch.parseXmlResult(xml_output) results = get_results_structure results[:source][:path] = File.dirname(test_file) results[:source][:file] = File.basename(test_file) # process test statistics xml_result = catch_xml.OverallResults # puts xml_result results[:counts][:total] = xml_result.totals results[:counts][:failed] = xml_result.failures results[:counts][:passed] = xml_result.successes results[:counts][:ignored] = xml_result.expectedFailures # remove test statistics lines output_string = unity_shell_result[:output].sub(CATCH_STDOUT_STATISTICS_PATTERN, '') output_string.lines do |line| # process unity output case line when /(:IGNORE)/ elements = extract_line_elements(line, results[:source][:file]) results[:ignores] << elements[0] results[:stdout] << elements[1] if (!elements[1].nil?) when /(:PASS$)/ elements = extract_line_elements(line, results[:source][:file]) results[:successes] << elements[0] results[:stdout] << elements[1] if (!elements[1].nil?) when /(:FAIL)/ elements = extract_line_elements(line, results[:source][:file]) results[:failures] << elements[0] results[:stdout] << elements[1] if (!elements[1].nil?) else # collect up all other results[:stdout] << line.chomp end end # @generator_test_results_sanity_checker.verify(results, unity_shell_result[:exit_code]) output_file = results_file.ext(@configurator.extension_testfail) if (results[:counts][:failed] > 0) @yaml_wrapper.dump(output_file, results) return { :result_file => output_file, :result => results } end def get_results_structure return { :source => {:path => '', :file => ''}, :successes => [], :failures => [], :ignores => [], :counts => {:total => 0, :passed => 0, :failed => 0, :ignored => 0}, :countsAsserts => {:total => 0, :passed => 0, :failed => 0, :ignored => 0}, :stdout => [], } end end CATCH_XML_STATISTICS_PATTERN = /<OverallResults successes="(\d+)" failures="(\d+)" expectedFailures="(\d+)"\/>/ CATCH_STDOUT_STATISTICS_PATTERN = /test cases:\s+(\d+)\s+[|]\s+(\d+)\s+passed\s+[|]\s+(\d+)\s+failed\s+assertions:\s+(\d+)\s+[|]\s+(\d+)\s+passed\s+[|]\s+(\d+)\s+failed\s*/i Parsed duplicate testcase error messages and forwarded them # Monkey patch the original require 'xml_parser' class GeneratorHelper # The only change to the original is the replaced regex match def test_results_error_handler(executable, shell_result) if (shell_result[:output].nil? or shell_result[:output].strip.empty?) error = true # mirror style of generic tool_executor failure output notice = "\n" + "ERROR: Test executable \"#{File.basename(executable)}\" failed.\n" + "> Produced no output to $stdout.\n" # elsif ((shell_result[:output] =~ CATCH_XML_STATISTICS_PATTERN).nil?) # error = true # # mirror style of generic tool_executor failure output # notice = "\n" + # "ERROR: Test executable \"#{File.basename(executable)}\" failed.\n" + # "> Produced no final test result counts in $stdout:\n" + # "#{shell_result[:output].strip}\n" end if (error) # since we told the tool executor to ignore the exit code, handle it explicitly here notice += "> And exited with status: [#{shell_result[:exit_code]}] (count of failed tests).\n" if (shell_result[:exit_code] != nil) notice += "> And then likely crashed.\n" if (shell_result[:exit_code] == nil) notice += "> This is often a symptom of a bad memory access in source or test code.\n\n" @streaminator.stderr_puts(notice, Verbosity::COMPLAIN) raise end end end # Monkey patch the original class GeneratorTestResults def process_and_write_results(unity_shell_result, results_file, test_file) output_file = results_file xml_output = unity_shell_result[:output] check_if_catch_successful(xml_output) catch_xml = Catch.parseXmlResult(xml_output) results = get_results_structure results[:source][:path] = File.dirname(test_file) results[:source][:file] = File.basename(test_file) # process test statistics xml_result = catch_xml.OverallResults # puts xml_result results[:counts][:total] = xml_result.totals results[:counts][:failed] = xml_result.failures results[:counts][:passed] = xml_result.successes results[:counts][:ignored] = xml_result.expectedFailures # remove test statistics lines output_string = unity_shell_result[:output].sub(CATCH_STDOUT_STATISTICS_PATTERN, '') catch_xml.Groups.each do |group| group.TestCases.each do |test_case| should_it_fail = test_case.tags =~ /\[!shouldfail\]/ sections = test_case.Sections if sections.length == 0 # Well, here we really don't have any substantial information result = test_case.OverallResult if result == true results[:successes] << 1 else results[:failures] << 1 end results[:stdout] << result.to_s else sections.each do |section| result = section.OverallResults results[:successes] << result.successes results[:failures] << result.failures results[:ignores] << result.expectedFailures results[:stdout] << result.to_s end end end end # @generator_test_results_sanity_checker.verify(results, unity_shell_result[:exit_code]) output_file = results_file.ext(@configurator.extension_testfail) if (results[:counts][:failed] > 0) @yaml_wrapper.dump(output_file, results) return { :result_file => output_file, :result => results } end def get_results_structure return { :source => {:path => '', :file => ''}, :successes => [], :failures => [], :ignores => [], :counts => {:total => 0, :passed => 0, :failed => 0, :ignored => 0}, # :countsAsserts => {:total => 0, :passed => 0, :failed => 0, :ignored => 0}, :stdout => [], } end private def check_if_catch_successful(output) match = output.match(/[\s\S]*?error:\s+TEST_CASE\(\s*"(.*?)"\s*\)\s+already\s+defined. \s+First\s+seen\s+at\s+([\w.\/]+):(\d+) \s+Redefined\s+at\s+([\w.\/]+):(\d+)/x) if (match) notice = "\nFATAL ERROR:\n" notice += %Q(One or more testcases have already been defined with the same name: "#{match[1]}"\n) notice += "Location #1: #{match[2]} @ line #{match[3]}\n" notice += "Location #2: #{match[4]} @ line #{match[5]}\n\n" # @ceedling[:streaminator].stderr_puts(notice, Verbosity::COMPLAIN) # @streaminator.stderr_puts(notice, Verbosity::COMPLAIN) raise notice end end end CATCH_XML_STATISTICS_PATTERN = /<OverallResults successes="(\d+)" failures="(\d+)" expectedFailures="(\d+)"\/>/ CATCH_STDOUT_STATISTICS_PATTERN = /test cases:\s+(\d+)\s+[|]\s+(\d+)\s+passed\s+[|]\s+(\d+)\s+failed\s+assertions:\s+(\d+)\s+[|]\s+(\d+)\s+passed\s+[|]\s+(\d+)\s+failed\s*/i
module CfnDsl VERSION = '0.11.3'.freeze end Patch release 0.11.4 module CfnDsl VERSION = '0.11.4'.freeze end
pipeline class (incomplete) require 'program' require 'settings' require 'json' class Pipeline def initialize(definition) # create a Pipeline instance from the # definition provided if Pipeline.can_parse? definition p = Pipeline.parse definition @name = p[:name] @description = p[:description] @programs = [] p[:programs].each do |program| # initialize the programs @programs << Program.load(program) end else raise "Can't parse pipeline definition" end end def self.exist?(name) # check if saved pipeline with name exists return File.exist?(File.join(CHAIN_DIR, name + CHAIN_EXT)) end def self.can_parse?(definition) JSON.parse definition true rescue JSON::ParserError, TypeError false end def self.parse(definition) # return hash from definition JSON.parse(definition) end def self.define(definition, name, description, inputs) # save definition for pipeline with name end def self.load(name) # return definition for pipeline with name Dir.chdir(CHAIN_DIR) do return File.open(name + CHAIN_EXT).readlines end end def self.run(name, inputs) # run pipelne by name if exist? name p = Pipeline.new(Pipeline.load(name)) p.run(inputs) end end def run(inputs) # run self puts '-' * 30 puts "Running pipeline: #{@name}..." puts '-' * 30 t1 = Time.now @programs.each do |program| output = program.run(inputs) inputs = output end puts "finished in #{Time.now - t1} seconds" end def self.list # list all pipeline definitions in store chainnames = [] Dir.chdir(CHAIN_DIR) do Dir['*.chain'].each do |chain| chainnames << chain end end chains = [] if chainnames.length > 0 puts '-' * 30 puts 'Installed chains:' puts '-' * 30 chainnames.each do |chain| c = Pipeline.load(File.basename(chain, CHAIN_EXT)) c = Pipeline.parse(c) chains << c Pipeline.print(c) end end return chains end def self.print(pipeline) # pretty-print pipeline puts "#{pipeline[:name]} (#{pipeline[:description]})" progs = "\t" pipeline[:programs].each_with_index do |p, j| progs += "\n\t" if j+1 % 3 == 0 progs += "#{j+1}. #{p} " end puts progs end end
class CIJoe class Campfire attr_reader :project_path, :build def initialize(project_path) @project_path = project_path if valid? require 'tinder' puts "Loaded Campfire notifier for #{project_path}." elsif ENV['RACK_ENV'] != 'test' puts "Can't load Campfire notifier for #{project_path}." puts "Please add the following to your project's .git/config:" puts "[campfire]" puts "\ttoken = abcd1234" puts "\tsubdomain = whatever" puts "\troom = Awesomeness" puts "\tssl = false" end end def campfire_config campfire_config = Config.new('campfire', project_path) @config = { :subdomain => campfire_config.subdomain.to_s, :token => campfire_config.token.to_s, :room => campfire_config.room.to_s, :ssl => campfire_config.ssl.to_s.strip == 'true' } end def valid? %w( subdomain token room ).all? do |key| !campfire_config[key.intern].empty? end end def notify(build) begin @build = build room.speak "#{short_message}. #{build.commit.url}" room.paste full_message if build.failed? room.leave rescue puts "Please check your campfire config for #{project_path}." end end private def room @room ||= begin config = campfire_config campfire = Tinder::Campfire.new(config[:subdomain], :token => config[:token], :ssl => config[:ssl] || false) campfire.find_room_by_name(config[:room]) end end def short_message "#{build.branch} at #{build.short_sha} of #{build.project} " + (build.worked? ? "passed" : "failed") + " (#{build.duration.to_i}s)" end def full_message <<-EOM Commit Message: #{build.commit.message} Commit Date: #{build.commit.committed_at} Commit Author: #{build.commit.author} #{build.clean_output} EOM end end end Cleaned up Campfire message. class CIJoe class Campfire attr_reader :project_path, :build def initialize(project_path) @project_path = project_path if valid? require 'tinder' puts "Loaded Campfire notifier for #{project_path}." elsif ENV['RACK_ENV'] != 'test' puts "Can't load Campfire notifier for #{project_path}." puts "Please add the following to your project's .git/config:" puts "[campfire]" puts "\ttoken = abcd1234" puts "\tsubdomain = whatever" puts "\troom = Awesomeness" puts "\tssl = false" end end def campfire_config campfire_config = Config.new('campfire', project_path) @config = { :subdomain => campfire_config.subdomain.to_s, :token => campfire_config.token.to_s, :room => campfire_config.room.to_s, :ssl => campfire_config.ssl.to_s.strip == 'true' } end def valid? %w( subdomain token room ).all? do |key| !campfire_config[key.intern].empty? end end def notify(build) begin @build = build room.speak "#{short_message}. #{build.commit.url}" room.paste full_message if build.failed? room.leave rescue puts "Please check your campfire config for #{project_path}." end end private def room @room ||= begin config = campfire_config campfire = Tinder::Campfire.new(config[:subdomain], :token => config[:token], :ssl => config[:ssl] || false) campfire.find_room_by_name(config[:room]) end end def short_message "[#{humanize(build.project)}] #{(build.worked? ? "Passed" : "***FAILED***")} on #{build.branch} at #{build.short_sha} (#{build.duration.to_i}s)" end def full_message <<-EOM Commit Message: #{build.commit.message} Commit Date: #{build.commit.committed_at} Commit Author: #{build.commit.author} #{build.clean_output} EOM end def humanize(lower_case_and_underscored_word) result = lower_case_and_underscored_word.to_s.dup inflections.humans.each { |(rule, replacement)| break if result.gsub!(rule, replacement) } result.gsub!(/_id$/, "") result.gsub!(/_/, ' ') result.gsub(/([a-z\d]*)/i) { |match| "#{inflections.acronyms[match] || match.downcase}" }.gsub(/^\w/) { $&.upcase } end end end
Gem::Specification.new do |spec| spec.name = 'internetkassa' spec.version = '0.9.2' spec.homepage = 'https://github.com/Fingertips/abn-amro_internetkassa/tree/master' spec.description = spec.summary = %{A library to make online payments using ABN-AMRO (Dutch bank) Internetkassa.} spec.author = 'Eloy Duran' spec.email = 'eloy@fngtps.com' spec.files = Dir['lib/**/*.rb', 'bin/*', '[A-Z]*', 'test/**/*', 'rails/init.rb'] spec.has_rdoc = true spec.extra_rdoc_files = %w{ README.rdoc LICENSE } spec.rdoc_options << '--charset=utf-8' << '--main=README.rdoc' if spec.respond_to?(:add_development_dependency) spec.add_development_dependency 'test-spec' spec.add_development_dependency 'mocha' end end And released 0.9.3 which explicitely specifies the files to include in the gem rather then using globs which github doesn't support. Gem::Specification.new do |spec| spec.name = 'internetkassa' spec.version = '0.9.3' spec.homepage = 'https://github.com/Fingertips/abn-amro_internetkassa/tree/master' spec.description = spec.summary = %{A library to make online payments using ABN-AMRO (Dutch bank) Internetkassa.} spec.author = 'Eloy Duran' spec.email = 'eloy@fngtps.com' spec.files = %w{ Rakefile README.rdoc LICENSE lib/abn-amro/internetkassa.rb lib/abn-amro/internetkassa/response.rb lib/abn-amro/internetkassa/response_codes.rb lib/abn-amro/internetkassa/helpers.rb rails/init.rb test/fixtures.rb test/helpers/fixtures_helper.rb test/helpers/view_helper.rb test/helpers_test.rb test/internetkassa_test.rb test/internetkassa_remote_test.rb test/response_test.rb test/response_regression_test.rb test/test_helper.rb } spec.has_rdoc = true spec.extra_rdoc_files = %w{ README.rdoc LICENSE } spec.rdoc_options << '--charset=utf-8' << '--main=README.rdoc' if spec.respond_to?(:add_development_dependency) spec.add_development_dependency 'test-spec' spec.add_development_dependency 'mocha' end end
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "health_inspector/version" # Allow to pass an arbitrary chef version. Useful for testing for example. chef_version = if ENV.key?('CHEF_VERSION') "= #{ENV['CHEF_VERSION']}" else ['>= 10', '<= 12'] end Gem::Specification.new do |s| s.name = "knife-inspect" s.version = HealthInspector::VERSION s.authors = ["Ben Marini"] s.email = ["bmarini@gmail.com"] s.homepage = "https://github.com/bmarini/knife-inspect" s.summary = %q{Inspect your chef repo as is compares to what is on your chef server} s.description = %q{Inspect your chef repo as is compares to what is on your chef server} s.rubyforge_project = "knife-inspect" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] s.add_development_dependency "rake" s.add_development_dependency "rspec" s.add_development_dependency "simplecov", "~> 0.8.2" s.add_runtime_dependency "chef", chef_version s.add_runtime_dependency "yajl-ruby" end Cleanup gemspec and add Greg Karékinian as new maintainer # -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "health_inspector/version" # Allow to pass an arbitrary chef version. Useful for testing for example. chef_version = if ENV.key?('CHEF_VERSION') "= #{ENV['CHEF_VERSION']}" else ['>= 10', '<= 12'] end Gem::Specification.new do |s| s.name = 'knife-inspect' s.version = HealthInspector::VERSION s.authors = ['Greg Karékinian', 'Ben Marini'] s.email = ['greg@karekinian.com'] s.homepage = 'https://github.com/bmarini/knife-inspect' s.summary = 'Inspect your chef repo as it is compared to what is on your chef server' s.description = 'Inspect your chef repo as it is compared to what is on your chef server' s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.add_development_dependency "rake" s.add_development_dependency "rspec" s.add_development_dependency "simplecov", "~> 0.8.2" s.add_runtime_dependency "chef", chef_version s.add_runtime_dependency "yajl-ruby" end
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "kontoapi-ruby" s.version = "0.2.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Jan Schwenzien"] s.date = "2012-04-08" s.description = "A ruby library to access the Konto API (https://www.kontoapi.de/), a webservice that performs validity checks and other services regarding german and international bank accounts." s.email = "jan@general-scripting.com" s.extra_rdoc_files = [ "LICENSE", "README.markdown" ] s.files = [ "Gemfile", "Gemfile.lock", "LICENSE", "README.markdown", "Rakefile", "VERSION", "kontoapi-ruby.gemspec", "lib/kontoapi-ruby.rb", "spec/kontoapi-ruby_spec.rb", "spec/spec_helper.rb" ] s.homepage = "http://github.com/GeneralScripting/kontoapi-ruby" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "1.8.15" s.summary = "Konto API Ruby Library" s.test_files = [ "spec/kontoapi-ruby_spec.rb", "spec/spec_helper.rb" ] if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<addressable>, [">= 0"]) s.add_runtime_dependency(%q<yajl-ruby>, [">= 0"]) s.add_development_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_development_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_development_dependency(%q<rcov>, [">= 0"]) s.add_development_dependency(%q<fakeweb>, [">= 0"]) else s.add_dependency(%q<addressable>, [">= 0"]) s.add_dependency(%q<yajl-ruby>, [">= 0"]) s.add_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<rcov>, [">= 0"]) s.add_dependency(%q<fakeweb>, [">= 0"]) end else s.add_dependency(%q<addressable>, [">= 0"]) s.add_dependency(%q<yajl-ruby>, [">= 0"]) s.add_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<rcov>, [">= 0"]) s.add_dependency(%q<fakeweb>, [">= 0"]) end end Regenerate gemspec for version 0.2.0 # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "kontoapi-ruby" s.version = "0.2.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Jan Schwenzien"] s.date = "2012-04-08" s.description = "A ruby library to access the Konto API (https://www.kontoapi.de/), a webservice that performs validity checks and other services regarding german bank accounts." s.email = "jan@general-scripting.com" s.extra_rdoc_files = [ "LICENSE", "README.markdown" ] s.files = [ "Gemfile", "Gemfile.lock", "LICENSE", "README.markdown", "Rakefile", "VERSION", "kontoapi-ruby.gemspec", "lib/kontoapi-ruby.rb", "spec/kontoapi-ruby_spec.rb", "spec/spec_helper.rb" ] s.homepage = "http://github.com/GeneralScripting/kontoapi-ruby" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "1.8.15" s.summary = "Konto API Ruby Library" s.test_files = [ "spec/kontoapi-ruby_spec.rb", "spec/spec_helper.rb" ] if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<addressable>, [">= 0"]) s.add_runtime_dependency(%q<yajl-ruby>, [">= 0"]) s.add_development_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_development_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_development_dependency(%q<rcov>, [">= 0"]) s.add_development_dependency(%q<fakeweb>, [">= 0"]) else s.add_dependency(%q<addressable>, [">= 0"]) s.add_dependency(%q<yajl-ruby>, [">= 0"]) s.add_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<rcov>, [">= 0"]) s.add_dependency(%q<fakeweb>, [">= 0"]) end else s.add_dependency(%q<addressable>, [">= 0"]) s.add_dependency(%q<yajl-ruby>, [">= 0"]) s.add_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<rcov>, [">= 0"]) s.add_dependency(%q<fakeweb>, [">= 0"]) end end
module CodeRay # = Tokens # # The Tokens class represents a list of tokens returnd from # a Scanner. # # A token is not a special object, just a two-element Array # consisting of # * the _token_ _kind_ (a Symbol representing the type of the token) # * the _token_ _text_ (the original source of the token in a String) # # A token looks like this: # # [:comment, '# It looks like this'] # [:float, '3.1415926'] # [:error, ''] # # Some scanners also yield some kind of sub-tokens, represented by special # token texts, namely :open and :close . # # The Ruby scanner, for example, splits "a string" into: # # [ # [:open, :string], # [:delimiter, '"'], # [:content, 'a string'], # [:delimiter, '"'], # [:close, :string] # ] # # Tokens is also the interface between Scanners and Encoders: # The input is split and saved into a Tokens object. The Encoder # then builds the output from this object. # # Thus, the syntax below becomes clear: # # CodeRay.scan('price = 2.59', :ruby).html # # the Tokens object is here -------^ # # See how small it is? ;) # # Tokens gives you the power to handle pre-scanned code very easily: # You can convert it to a webpage, a YAML file, or dump it into a gzip'ed string # that you put in your DB. # # Tokens' subclass TokenStream allows streaming to save memory. class Tokens < Array class << self # Convert the token to a string. # # This format is used by Encoders.Tokens. # It can be reverted using read_token. def write_token text, type if text.is_a? String "#{type}\t#{escape(text)}\n" else ":#{text}\t#{type}\t\n" end end # Read a token from the string. # # Inversion of write_token. # # TODO Test this! def read_token token type, text = token.split("\t", 2) if type[0] == ?: [text.to_sym, type[1..-1].to_sym] else [type.to_sym, unescape(text)] end end # Escapes a string for use in write_token. def escape text text.gsub(/[\n\\]/, '\\\\\&') end # Unescapes a string created by escape. def unescape text text.gsub(/\\[\n\\]/) { |m| m[1,1] } end end # Whether the object is a TokenStream. # # Returns false. def stream? false end # Iterates over all tokens. # # If a filter is given, only tokens of that kind are yielded. def each kind_filter = nil, &block unless kind_filter super(&block) else super do |text, kind| next unless kind == kind_filter yield text, kind end end end # Iterates over all text tokens. # Range tokens like [:open, :string] are left out. # # Example: # tokens.each_text_token { |text, kind| text.replace html_escape(text) } def each_text_token each do |text, kind| next unless text.respond_to? :to_str yield text, kind end end # Encode the tokens using encoder. # # encoder can be # * a symbol like :html oder :statistic # * an Encoder class # * an Encoder object # # options are passed to the encoder. def encode encoder, options = {} unless encoder.is_a? Encoders::Encoder unless encoder.is_a? Class encoder_class = Encoders[encoder] end encoder = encoder_class.new options end encoder.encode_tokens self, options end # Turn into a string using Encoders::Text. # # +options+ are passed to the encoder if given. def to_s options = {} encode :text, options end # Redirects unknown methods to encoder calls. # # For example, if you call +tokens.html+, the HTML encoder # is used to highlight the tokens. def method_missing meth, options = {} Encoders[meth].new(options).encode_tokens self end # Returns the tokens compressed by joining consecutive # tokens of the same kind. # # This can not be undone, but should yield the same output # in most Encoders. It basically makes the output smaller. # # Combined with dump, it saves space for the cost # calculating time. # # If the scanner is written carefully, this is not required - # for example, consecutive //-comment lines can already be # joined in one token by the Scanner. def optimize print ' Tokens#optimize: before: %d - ' % size if $DEBUG last_kind = last_text = nil new = self.class.new each do |text, kind| if text.is_a? String if kind == last_kind last_text << text else new << [last_text, last_kind] if last_kind last_text = text last_kind = kind end else new << [last_text, last_kind] if last_kind last_kind = last_text = nil new << [text, kind] end end new << [last_text, last_kind] if last_kind print 'after: %d (%d saved = %2.0f%%)' % [new.size, size - new.size, 1.0 - (new.size.to_f / size)] if $DEBUG new end # Compact the object itself; see optimize. def optimize! replace optimize end # Dumps the object into a String that can be saved # in files or databases. # # The dump is created with Marshal.dump; # In addition, it is gzipped using GZip.gzip. # # The returned String object includes Undumping # so it has an #undump method. See Tokens.load. # # You can configure the level of compression, # but the default value 7 should be what you want # in most cases as it is a good comprimise between # speed and compression rate. # # See GZip module. def dump gzip_level = 7 require 'coderay/helpers/gzip_simple' dump = Marshal.dump self dump = dump.gzip gzip_level dump.extend Undumping end # The total size of the tokens; # Should be equal to the input size before # scanning. def text_size map { |t, k| t }.join.size end # Include this module to give an object an #undump # method. # # The string returned by Tokens.dump includes Undumping. module Undumping # Calls Tokens.load with itself. def undump Tokens.load self end end # Undump the object using Marshal.load, then # unzip it using GZip.gunzip. # # The result is commonly a Tokens object, but # this is not guaranteed. def Tokens.load dump require 'coderay/helpers/gzip_simple' dump = dump.gunzip @dump = Marshal.load dump end end # = TokenStream # # The TokenStream class is a fake Array without elements. # # It redirects the method << to a block given at creation. # # This allows scanners and Encoders to use streaming (no # tokens are saved, the input is highlighted the same time it # is scanned) with the same code. # # See CodeRay.encode_stream and CodeRay.scan_stream class TokenStream < Tokens # Whether the object is a TokenStream. # # Returns true. def stream? true end # The Array is empty, but size counts the tokens given by <<. attr_reader :size # Creates a new TokenStream that calls +block+ whenever # its << method is called. # # Example: # # require 'coderay' # # token_stream = CodeRay::TokenStream.new do |kind, text| # puts 'kind: %s, text size: %d.' % [kind, text.size] # end # # token_stream << [:regexp, '/\d+/'] # #-> kind: rexpexp, text size: 5. # def initialize &block raise ArgumentError, 'Block expected for streaming.' unless block @callback = block @size = 0 end # Calls +block+ with +token+ and increments size. # # Returns self. def << token @callback.call token @size += 1 self end # This method is not implemented due to speed reasons. Use Tokens. def text_size raise NotImplementedError, 'This method is not implemented due to speed reasons.' end # A TokenStream cannot be dumped. Use Tokens. def dump raise NotImplementedError, 'A TokenStream cannot be dumped.' end # A TokenStream cannot be optimized. Use Tokens. def optimize raise NotImplementedError, 'A TokenStream cannot be optimized.' end end end First victim of the Demo Tests: Bugfix in tokens.rb! module CodeRay # = Tokens # # The Tokens class represents a list of tokens returnd from # a Scanner. # # A token is not a special object, just a two-element Array # consisting of # * the _token_ _kind_ (a Symbol representing the type of the token) # * the _token_ _text_ (the original source of the token in a String) # # A token looks like this: # # [:comment, '# It looks like this'] # [:float, '3.1415926'] # [:error, ''] # # Some scanners also yield some kind of sub-tokens, represented by special # token texts, namely :open and :close . # # The Ruby scanner, for example, splits "a string" into: # # [ # [:open, :string], # [:delimiter, '"'], # [:content, 'a string'], # [:delimiter, '"'], # [:close, :string] # ] # # Tokens is also the interface between Scanners and Encoders: # The input is split and saved into a Tokens object. The Encoder # then builds the output from this object. # # Thus, the syntax below becomes clear: # # CodeRay.scan('price = 2.59', :ruby).html # # the Tokens object is here -------^ # # See how small it is? ;) # # Tokens gives you the power to handle pre-scanned code very easily: # You can convert it to a webpage, a YAML file, or dump it into a gzip'ed string # that you put in your DB. # # Tokens' subclass TokenStream allows streaming to save memory. class Tokens < Array class << self # Convert the token to a string. # # This format is used by Encoders.Tokens. # It can be reverted using read_token. def write_token text, type if text.is_a? String "#{type}\t#{escape(text)}\n" else ":#{text}\t#{type}\t\n" end end # Read a token from the string. # # Inversion of write_token. # # TODO Test this! def read_token token type, text = token.split("\t", 2) if type[0] == ?: [text.to_sym, type[1..-1].to_sym] else [type.to_sym, unescape(text)] end end # Escapes a string for use in write_token. def escape text text.gsub(/[\n\\]/, '\\\\\&') end # Unescapes a string created by escape. def unescape text text.gsub(/\\[\n\\]/) { |m| m[1,1] } end end # Whether the object is a TokenStream. # # Returns false. def stream? false end # Iterates over all tokens. # # If a filter is given, only tokens of that kind are yielded. def each kind_filter = nil, &block unless kind_filter super(&block) else super() do |text, kind| next unless kind == kind_filter yield text, kind end end end # Iterates over all text tokens. # Range tokens like [:open, :string] are left out. # # Example: # tokens.each_text_token { |text, kind| text.replace html_escape(text) } def each_text_token each do |text, kind| next unless text.respond_to? :to_str yield text, kind end end # Encode the tokens using encoder. # # encoder can be # * a symbol like :html oder :statistic # * an Encoder class # * an Encoder object # # options are passed to the encoder. def encode encoder, options = {} unless encoder.is_a? Encoders::Encoder unless encoder.is_a? Class encoder_class = Encoders[encoder] end encoder = encoder_class.new options end encoder.encode_tokens self, options end # Turn into a string using Encoders::Text. # # +options+ are passed to the encoder if given. def to_s options = {} encode :text, options end # Redirects unknown methods to encoder calls. # # For example, if you call +tokens.html+, the HTML encoder # is used to highlight the tokens. def method_missing meth, options = {} Encoders[meth].new(options).encode_tokens self end # Returns the tokens compressed by joining consecutive # tokens of the same kind. # # This can not be undone, but should yield the same output # in most Encoders. It basically makes the output smaller. # # Combined with dump, it saves space for the cost # calculating time. # # If the scanner is written carefully, this is not required - # for example, consecutive //-comment lines can already be # joined in one token by the Scanner. def optimize print ' Tokens#optimize: before: %d - ' % size if $DEBUG last_kind = last_text = nil new = self.class.new each do |text, kind| if text.is_a? String if kind == last_kind last_text << text else new << [last_text, last_kind] if last_kind last_text = text last_kind = kind end else new << [last_text, last_kind] if last_kind last_kind = last_text = nil new << [text, kind] end end new << [last_text, last_kind] if last_kind print 'after: %d (%d saved = %2.0f%%)' % [new.size, size - new.size, 1.0 - (new.size.to_f / size)] if $DEBUG new end # Compact the object itself; see optimize. def optimize! replace optimize end # Dumps the object into a String that can be saved # in files or databases. # # The dump is created with Marshal.dump; # In addition, it is gzipped using GZip.gzip. # # The returned String object includes Undumping # so it has an #undump method. See Tokens.load. # # You can configure the level of compression, # but the default value 7 should be what you want # in most cases as it is a good comprimise between # speed and compression rate. # # See GZip module. def dump gzip_level = 7 require 'coderay/helpers/gzip_simple' dump = Marshal.dump self dump = dump.gzip gzip_level dump.extend Undumping end # The total size of the tokens; # Should be equal to the input size before # scanning. def text_size map { |t, k| t }.join.size end # Include this module to give an object an #undump # method. # # The string returned by Tokens.dump includes Undumping. module Undumping # Calls Tokens.load with itself. def undump Tokens.load self end end # Undump the object using Marshal.load, then # unzip it using GZip.gunzip. # # The result is commonly a Tokens object, but # this is not guaranteed. def Tokens.load dump require 'coderay/helpers/gzip_simple' dump = dump.gunzip @dump = Marshal.load dump end end # = TokenStream # # The TokenStream class is a fake Array without elements. # # It redirects the method << to a block given at creation. # # This allows scanners and Encoders to use streaming (no # tokens are saved, the input is highlighted the same time it # is scanned) with the same code. # # See CodeRay.encode_stream and CodeRay.scan_stream class TokenStream < Tokens # Whether the object is a TokenStream. # # Returns true. def stream? true end # The Array is empty, but size counts the tokens given by <<. attr_reader :size # Creates a new TokenStream that calls +block+ whenever # its << method is called. # # Example: # # require 'coderay' # # token_stream = CodeRay::TokenStream.new do |kind, text| # puts 'kind: %s, text size: %d.' % [kind, text.size] # end # # token_stream << [:regexp, '/\d+/'] # #-> kind: rexpexp, text size: 5. # def initialize &block raise ArgumentError, 'Block expected for streaming.' unless block @callback = block @size = 0 end # Calls +block+ with +token+ and increments size. # # Returns self. def << token @callback.call token @size += 1 self end # This method is not implemented due to speed reasons. Use Tokens. def text_size raise NotImplementedError, 'This method is not implemented due to speed reasons.' end # A TokenStream cannot be dumped. Use Tokens. def dump raise NotImplementedError, 'A TokenStream cannot be dumped.' end # A TokenStream cannot be optimized. Use Tokens. def optimize raise NotImplementedError, 'A TokenStream cannot be optimized.' end end end
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{averager} s.version = "0.1.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Tobias Schwab"] s.date = %q{2010-11-02} s.description = %q{RubyGem to track long running processes.} s.email = %q{tobias.schwab@dynport.de} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".bundle/config", ".rspec", "Gemfile", "Gemfile.lock", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "averager.gemspec", "lib/averager.rb", "spec/averager_spec.rb", "spec/spec_helper.rb", "spec/time_travel.rb" ] s.homepage = %q{http://github.com/tobstarr/averager} s.require_paths = ["lib"] s.rubygems_version = %q{1.3.7} s.summary = %q{RubyGem to track long running processes.} s.test_files = [ "spec/averager_spec.rb", "spec/spec_helper.rb", "spec/time_travel.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<ruby-debug19>, [">= 0"]) s.add_development_dependency(%q<rspec>, [">= 2.0.0.beta.19"]) s.add_development_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.5.0.pre3"]) s.add_development_dependency(%q<rcov>, [">= 0"]) s.add_development_dependency(%q<rspec>, [">= 2.0.0.beta.19"]) s.add_development_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.5.0.pre3"]) s.add_development_dependency(%q<rcov>, [">= 0"]) else s.add_dependency(%q<ruby-debug19>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 2.0.0.beta.19"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.0.pre3"]) s.add_dependency(%q<rcov>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 2.0.0.beta.19"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.0.pre3"]) s.add_dependency(%q<rcov>, [">= 0"]) end else s.add_dependency(%q<ruby-debug19>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 2.0.0.beta.19"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.0.pre3"]) s.add_dependency(%q<rcov>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 2.0.0.beta.19"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.0.pre3"]) s.add_dependency(%q<rcov>, [">= 0"]) end end bump version # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{averager} s.version = "0.2.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Tobias Schwab"] s.date = %q{2010-11-03} s.description = %q{RubyGem to track long running processes.} s.email = %q{tobias.schwab@dynport.de} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".bundle/config", ".rspec", "Gemfile", "Gemfile.lock", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "averager.gemspec", "lib/averager.rb", "spec/averager_spec.rb", "spec/spec_helper.rb", "spec/time_travel.rb" ] s.homepage = %q{http://github.com/tobstarr/averager} s.require_paths = ["lib"] s.rubygems_version = %q{1.3.7} s.summary = %q{RubyGem to track long running processes.} s.test_files = [ "spec/averager_spec.rb", "spec/spec_helper.rb", "spec/time_travel.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<ruby-debug>, [">= 0"]) s.add_development_dependency(%q<rspec>, [">= 2.0.0.beta.19"]) s.add_development_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.5.0.pre3"]) s.add_development_dependency(%q<rcov>, [">= 0"]) s.add_development_dependency(%q<rspec>, [">= 2.0.0.beta.19"]) s.add_development_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.5.0.pre3"]) s.add_development_dependency(%q<rcov>, [">= 0"]) else s.add_dependency(%q<ruby-debug>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 2.0.0.beta.19"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.0.pre3"]) s.add_dependency(%q<rcov>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 2.0.0.beta.19"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.0.pre3"]) s.add_dependency(%q<rcov>, [">= 0"]) end else s.add_dependency(%q<ruby-debug>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 2.0.0.beta.19"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.0.pre3"]) s.add_dependency(%q<rcov>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 2.0.0.beta.19"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.0.pre3"]) s.add_dependency(%q<rcov>, [">= 0"]) end end
require "conred/version" module Conred module Helpers extend self def action_view @action_view = ActionView::Base.new end def sanitize_and_trim(text = "", word_count = nil, omission = '...') text = action_view.strip_tags(text) if word_count action_view.truncate(text, :length => word_count, :omission => omission).html_safe else text.html_safe end end def sanitize_body(text) text = action_view.sanitize(text, :tags => %w(p a strong ul ol li blockquote strike u em), :attributes => %w(href)) text.html_safe end def external_url(link) /^http/.match(link) ? link : "http://#{link}" end end end Fixed conred gem require "conred/version" module Conred module Helpers extend self def action_view @action_view ||= ActionView::Base.new end def sanitize_and_trim(text = "", word_count = nil, omission = '...') text = action_view.strip_tags(text) if word_count action_view.truncate(text, :length => word_count, :omission => omission).html_safe elsif text == nil "" else text.html_safe end end def sanitize_body(text) text = action_view.sanitize(text, :tags => %w(p a strong ul ol li blockquote strike u em), :attributes => %w(href)) text.html_safe end def external_url(link) /^http/.match(link) ? link : "http://#{link}" end end end
class SwarmsController < ApplicationController before_filter :scope_to_swarm, :except => %w{index new create} before_filter :check_for_user, :except => %w{index show} respond_to :html, :json def index @swarms = Swarm.all end def show if @swarm.closed? if params[:page] @current_page = params[:page].to_i else @current_page = 1 end @rows, @total_pages = @swarm.search.all(@current_page, 10) end respond_with @swarm end def delete end def destroy @swarm.destroy redirect_to swarms_path end def new @swarm = Swarm.new end def fields end def update_fields @swarm.update(:fields => params[:fields]) if params[:update_and_next] redirect_to preview_swarm_path(@swarm) else redirect_to edit_swarm_path(@swarm) end end def preview end def embed render layout: 'embed' end def create swarm = Swarm.new(swarm_params) swarm.user = @current_user swarm.save redirect_to fields_swarm_path(swarm) end def edit end def update @swarm.update(swarm_params) redirect_to fields_swarm_path(@swarm) end def open open_time = Time.new(params['open_year'], params['open_month'], params['open_day'], params['open_hour'], params['open_minute']) @swarm.update(:opens_at => open_time) redirect_to @swarm end def close close_time = Time.new(params['close_year'], params['close_month'], params['close_day'], params['close_hour'], params['close_minute']) if @swarm.opens_at && (@swarm.opens_at > close_time) flash[:error] = "Swarm cannot close before it has opened!" else @swarm.update(:closes_at => close_time) end redirect_to @swarm end def clone new_swarm = @swarm.dup new_swarm.opens_at = nil new_swarm.closes_at = nil new_swarm.name = @swarm.name + " (cloned)" new_swarm.save redirect_to new_swarm end private def scope_to_swarm @swarm = Swarm.find(params[:id]) end def swarm_params params.require(:swarm).permit(:name, :description) end end Embed shouldn't need authentication. class SwarmsController < ApplicationController before_filter :scope_to_swarm, :except => %w{index new create} before_filter :check_for_user, :except => %w{index show embed} respond_to :html, :json def index @swarms = Swarm.all end def show if @swarm.closed? if params[:page] @current_page = params[:page].to_i else @current_page = 1 end @rows, @total_pages = @swarm.search.all(@current_page, 10) end respond_with @swarm end def delete end def destroy @swarm.destroy redirect_to swarms_path end def new @swarm = Swarm.new end def fields end def update_fields @swarm.update(:fields => params[:fields]) if params[:update_and_next] redirect_to preview_swarm_path(@swarm) else redirect_to edit_swarm_path(@swarm) end end def preview end def embed render layout: 'embed' end def create swarm = Swarm.new(swarm_params) swarm.user = @current_user swarm.save redirect_to fields_swarm_path(swarm) end def edit end def update @swarm.update(swarm_params) redirect_to fields_swarm_path(@swarm) end def open open_time = Time.new(params['open_year'], params['open_month'], params['open_day'], params['open_hour'], params['open_minute']) @swarm.update(:opens_at => open_time) redirect_to @swarm end def close close_time = Time.new(params['close_year'], params['close_month'], params['close_day'], params['close_hour'], params['close_minute']) if @swarm.opens_at && (@swarm.opens_at > close_time) flash[:error] = "Swarm cannot close before it has opened!" else @swarm.update(:closes_at => close_time) end redirect_to @swarm end def clone new_swarm = @swarm.dup new_swarm.opens_at = nil new_swarm.closes_at = nil new_swarm.name = @swarm.name + " (cloned)" new_swarm.save redirect_to new_swarm end private def scope_to_swarm @swarm = Swarm.find(params[:id]) end def swarm_params params.require(:swarm).permit(:name, :description) end end
#!/usr/bin/env ruby require 'thread' require 'Qt' require './Graph' require './Point' #require './TraceConverter' class DrawBox < Qt::Widget def initialize(parent, mode) super @g = Graph.new("alphabet.json") @result @pos1 @pos2 @parent = parent @image = Qt::Image.new @parent.width, @parent.height/2, 7 @image.fill Qt::Color.new "#ffffff" end def paintEvent(e) painter = Qt::Painter.new painter.begin self painter.setRenderHint Qt::Painter::Antialiasing dirtyRect = e.rect painter.drawImage(dirtyRect, @image, dirtyRect) painter.end end def mouseMoveEvent(e) if (e.pos.x > 0 and e.pos.x < @image.width) and (e.pos.y > 0 and e.pos.y < @image.height) @pos2 = e.pos @result << Point.new(@pos2.x, @pos2.y) #puts "Pos : x : #{@pos1.x}, y : #{@pos1.y}" drawLineTo @pos1, @pos2 #drawPoint @pos1 @pos1 = @pos2 end end def mousePressEvent(e) @result = Array.new @pos1 = e.pos @result << Point.new(@pos1.x, @pos1.y) end def mouseReleaseEvent(e) @image.fill Qt::Color.new "#ffffff" # @result.each{|p| puts p} if @result.length > 19 r = @parent.getResult r.insert(@g.solve(@result)) end # puts @result.length # tc = TraceConverter.new(@result) # tab = tc.resize # file = File.open('alphabet.json', 'a') # str = '{"letter":"a", "points":[' # tab.each{|p| str+='{"x":'+p.x.to_s+', "y":'+p.y.to_s+'},'} # str = str[0..-2] # str+= ']},' # file.puts str # file.close update end def drawLineTo pos1, pos2 p = Qt::Painter.new p.begin @image p.setRenderHint Qt::Painter::Antialiasing color = Qt::Color.new color.setNamedColor "#333333" pen = Qt::Pen.new color pen.setWidth 3 p.setPen pen p.drawLine Qt::Line.new(pos1, pos2) rad = (3/2)+2; update(Qt::Rect.new(pos1, pos2).normalized().adjusted(-rad, -rad, +rad, +rad)) p.end end def drawPoint pos1 p = Qt::Painter.new p.begin @image p.setRenderHint Qt::Painter::Antialiasing color = Qt::Color.new color.setNamedColor "#333333" pen = Qt::Pen.new color pen.setWidth 3 p.setPen pen p.drawPoint pos1.x, pos1.y rad = (3/2)+2; update p.end end end drabow #!/usr/bin/env ruby require 'thread' require 'Qt' require './Graph' require './Point' #require './TraceConverter' class DrawBox < Qt::Widget def initialize(parent, mode) super parent @g = Graph.new("alphabet.json") @result @pos1 @pos2 @parent = parent @image = Qt::Image.new 300, 300, 7 @image.fill Qt::Color.new "#ffffff" end def paintEvent(e) painter = Qt::Painter.new painter.begin self painter.setRenderHint Qt::Painter::Antialiasing dirtyRect = e.rect painter.drawImage(dirtyRect, @image, dirtyRect) painter.end end def mouseMoveEvent(e) if (e.pos.x > 0 and e.pos.x < @image.width) and (e.pos.y > 0 and e.pos.y < @image.height) @pos2 = e.pos @result << Point.new(@pos2.x, @pos2.y) #puts "Pos : x : #{@pos1.x}, y : #{@pos1.y}" drawLineTo @pos1, @pos2 #drawPoint @pos1 @pos1 = @pos2 end end def mousePressEvent(e) @result = Array.new @pos1 = e.pos @result << Point.new(@pos1.x, @pos1.y) end def mouseReleaseEvent(e) @image.fill Qt::Color.new "#ffffff" # @result.each{|p| puts p} if @result.length > 19 r = @parent.getResult r.insert(@g.solve(@result)) end # puts @result.length # tc = TraceConverter.new(@result) # tab = tc.resize # file = File.open('alphabet.json', 'a') # str = '{"letter":"a", "points":[' # tab.each{|p| str+='{"x":'+p.x.to_s+', "y":'+p.y.to_s+'},'} # str = str[0..-2] # str+= ']},' # file.puts str # file.close update end def drawLineTo pos1, pos2 p = Qt::Painter.new p.begin @image p.setRenderHint Qt::Painter::Antialiasing color = Qt::Color.new color.setNamedColor "#333333" pen = Qt::Pen.new color pen.setWidth 3 p.setPen pen p.drawLine Qt::Line.new(pos1, pos2) rad = (3/2)+2; update(Qt::Rect.new(pos1, pos2).normalized().adjusted(-rad, -rad, +rad, +rad)) p.end end def drawPoint pos1 p = Qt::Painter.new p.begin @image p.setRenderHint Qt::Painter::Antialiasing color = Qt::Color.new color.setNamedColor "#333333" pen = Qt::Pen.new color pen.setWidth 3 p.setPen pen p.drawPoint pos1.x, pos1.y rad = (3/2)+2; update p.end end end
class TreeToGraph # Public: Creates a Turbine graph to represent the given hash structure. # # nodes - An array of nodes to be added to the graph. Each element in the # array should have a unique :name key to identify the node, and an # optional :children key containing an array of child nodes. # techs - A hash where each key matches the key of a node, and each value is # an array of technologies connected to the node. Optional. # # For example: # # nodes = YAML.load(<<-EOS.gsub(/ /, '')) # --- # name: HV Network # children: # - name: MV Network # children: # - name: "LV #1" # - name: "LV #2" # - name: "LV #3" # EOS # # ETLoader.build(structure) # # => #<Turbine::Graph (5 nodes, 4 edges)> # # Returns a Turbine::Graph. def self.convert(tree, techs = {}) new(tree, techs).to_graph end # Internal: Converts the tree and technologies into a Turbine::Graph. def to_graph @graph ||= build_graph end ####### private ####### def initialize(tree, techs) @tree = tree @techs = techs end # Internal: Creates a new graph using the tree and technologies hash given to # the TreeToGraph. def build_graph graph = Turbine::Graph.new build_node(@tree, nil, graph) graph end # Internal: Builds a single node from the tree hash, and recurses through and # child nodes. def build_node(attrs, parent = nil, graph = Turbine::Graph.new) attrs = attrs.symbolize_keys children = attrs.delete(:children) || [] node = graph.add(Turbine::Node.new(attrs.delete(:name), attrs)) # Parent connection. parent.connect_to(node, :energy) if parent # Consumers and suppliers. if (techs = techs(node.key)).any? node.set(:load, techs.map do |tech| Rational((tech[:load] || 0.0).to_s) end.compact.reduce(:+)) elsif children.none? node.set(:load, Rational('0.0')) end # Children children.each { |c| build_node(c, node, graph) } end # Internal: Returns an array of hashes, each one containing details of # technologies attached to the node. def techs(node_key) (@techs[node_key] || []).map(&:symbolize_keys) end end # TreeToGraph Don't break if given an empty tree class TreeToGraph # Public: Creates a Turbine graph to represent the given hash structure. # # nodes - An array of nodes to be added to the graph. Each element in the # array should have a unique :name key to identify the node, and an # optional :children key containing an array of child nodes. # techs - A hash where each key matches the key of a node, and each value is # an array of technologies connected to the node. Optional. # # For example: # # nodes = YAML.load(<<-EOS.gsub(/ /, '')) # --- # name: HV Network # children: # - name: MV Network # children: # - name: "LV #1" # - name: "LV #2" # - name: "LV #3" # EOS # # ETLoader.build(structure) # # => #<Turbine::Graph (5 nodes, 4 edges)> # # Returns a Turbine::Graph. def self.convert(tree, techs = {}) new(tree, techs).to_graph end # Internal: Converts the tree and technologies into a Turbine::Graph. def to_graph @graph ||= build_graph end ####### private ####### def initialize(tree, techs) @tree = tree || {} @techs = techs end # Internal: Creates a new graph using the tree and technologies hash given to # the TreeToGraph. def build_graph graph = Turbine::Graph.new build_node(@tree, nil, graph) graph end # Internal: Builds a single node from the tree hash, and recurses through and # child nodes. def build_node(attrs, parent = nil, graph = Turbine::Graph.new) attrs = attrs.symbolize_keys children = attrs.delete(:children) || [] node = graph.add(Turbine::Node.new(attrs.delete(:name), attrs)) # Parent connection. parent.connect_to(node, :energy) if parent # Consumers and suppliers. if (techs = techs(node.key)).any? node.set(:load, techs.map do |tech| Rational((tech[:load] || 0.0).to_s) end.compact.reduce(:+)) elsif children.none? node.set(:load, Rational('0.0')) end # Children children.each { |c| build_node(c, node, graph) } end # Internal: Returns an array of hashes, each one containing details of # technologies attached to the node. def techs(node_key) (@techs[node_key] || []).map(&:symbolize_keys) end end # TreeToGraph
module Cubits VERSION = '0.0.1' end Version is now v0.1.0 module Cubits VERSION = '0.1.0' end
#!/usr/bin/env ruby # ----------------------------------------------------------------------------- # # File: textpad.rb # Description: A class that displays text using a pad. # The motivation for this is to put formatted text and not care about truncating and # stuff. Also, there will be only one write, not each time scrolling happens. # I found textview code for repaint being more complex than required. # Author: rkumar http://github.com/rkumar/mancurses/ # Date: 2011-11-09 - 16:59 # License: Same as Ruby's License (http://www.ruby-lang.org/LICENSE.txt) # Last update: 2013-03-16 17:10 # # == CHANGES # == TODO # _ in popup case allowing scrolling when it should not so you get an extra char at end # _ The list one needs a f-char like functionality. # x handle putting data again and overwriting existing # When reputting data, the underlying pad needs to be properly cleared # esp last row and last col # # x add mappings and process key in handle_keys and other widget things # - can pad movement and other ops be abstracted into module for reuse # / get scrolling like in vim (C-f e y b d) # # == TODO 2013-03-07 - 20:34 # _ key bindings not showing up -- bind properly # ----------------------------------------------------------------------------- # # require 'rbcurse' require 'rbcurse/core/include/bordertitle' include RubyCurses module Cygnus extend self class TextPad < Widget include BorderTitle dsl_accessor :suppress_border attr_reader :current_index attr_reader :rows , :cols # You may pass height, width, row and col for creating a window otherwise a fullscreen window # will be created. If you pass a window from caller then that window will be used. # Some keys are trapped, jkhl space, pgup, pgdown, end, home, t b # This is currently very minimal and was created to get me started to integrating # pads into other classes such as textview. def initialize form=nil, config={}, &block @editable = false @focusable = true @config = config @row = @col = 0 @prow = @pcol = 0 @startrow = 0 @startcol = 0 @list = [] super ## NOTE # --------------------------------------------------- # Since we are using pads, you need to get your height, width and rows correct # Make sure the height factors in the row, else nothing may show # --------------------------------------------------- #@height = @height.ifzero(FFI::NCurses.LINES) #@width = @width.ifzero(FFI::NCurses.COLS) @rows = @height @cols = @width # NOTE XXX if cols is > COLS then padrefresh can fail @startrow = @row @startcol = @col #@suppress_border = config[:suppress_border] @row_offset = @col_offset = 1 unless @suppress_border @startrow += 1 @startcol += 1 @rows -=3 # 3 is since print_border_only reduces one from width, to check whether this is correct @cols -=3 else # seeing why nothing is printing @rows -=0 # 3 is since print_border_only reduces one from width, to check whether this is correct ## if next is 0 then padrefresh doesn't print @cols -=1 end @row_offset = @col_offset = 0 if @suppress_borders @top = @row @left = @col @lastrow = @row + 1 @lastcol = @col + 1 @_events << :PRESS @_events << :ENTER_ROW @scrollatrows = @height - 3 init_vars end def init_vars $multiplier = 0 @oldindex = @current_index = 0 # column cursor @prow = @pcol = @curpos = 0 if @row && @col @lastrow = @row + 1 @lastcol = @col + 1 end @repaint_required = true end def rowcol #:nodoc: return @row+@row_offset, @col+@col_offset end private ## XXX in list text returns the selected row, list returns the full thing, keep consistent def create_pad destroy if @pad #@pad = FFI::NCurses.newpad(@content_rows, @content_cols) @pad = @window.get_pad(@content_rows, @content_cols ) end private # create and populate pad def populate_pad @_populate_needed = false # how can we make this more sensible ? FIXME #@renderer ||= DefaultFileRenderer.new #if ".rb" == @filetype @content_rows = @content.count @content_cols = content_cols() # this should be explicit and not "intelligent" #@title += " [ #{@content_rows},#{@content_cols}] " if @cols > 50 @content_rows = @rows if @content_rows < @rows @content_cols = @cols if @content_cols < @cols #$log.debug "XXXX content_cols = #{@content_cols}" create_pad # clearstring is the string required to clear the pad to backgroud color @clearstring = nil cp = get_color($datacolor, @color, @bgcolor) @cp = FFI::NCurses.COLOR_PAIR(cp) if cp != $datacolor @clearstring ||= " " * @width end Ncurses::Panel.update_panels @content.each_index { |ix| #FFI::NCurses.mvwaddstr(@pad,ix, 0, @content[ix]) render @pad, ix, @content[ix] } end public # supply a custom renderer that implements +render()+ # @see render def renderer r @renderer = r end # # default method for rendering a line # def render pad, lineno, text if text.is_a? Chunks::ChunkLine FFI::NCurses.wmove @pad, lineno, 0 a = get_attrib @attrib show_colored_chunks text, nil, a return end if @renderer @renderer.render @pad, lineno, text else ## messabox does have a method to paint the whole window in bg color its in rwidget.rb att = NORMAL FFI::NCurses.wattron(@pad, @cp | att) FFI::NCurses.mvwaddstr(@pad,lineno, 0, @clearstring) if @clearstring FFI::NCurses.mvwaddstr(@pad,lineno, 0, @content[lineno]) #FFI::NCurses.mvwaddstr(pad, lineno, 0, text) FFI::NCurses.wattroff(@pad, @cp | att) end end # supply a filename as source for textpad # Reads up file into @content def filename(filename) @file = filename unless File.exists? filename alert "#{filename} does not exist" return end @filetype = File.extname filename @content = File.open(filename,"r").readlines if @filetype == "" if @content.first.index("ruby") @filetype = ".rb" end end init_vars @repaint_all = true @_populate_needed = true end # Supply an array of string to be displayed # This will replace existing text ## XXX in list text returns the selected row, list returns the full thing, keep consistent def text lines raise "text() receiving null content" unless lines @content = lines @_populate_needed = true @repaint_all = true init_vars end alias :list :text def content raise "content is nil " unless @content return @content end ## ---- the next 2 methods deal with printing chunks # we should put it int a common module and include it # in Window and Pad stuff and perhaps include it conditionally. ## 2013-03-07 - 19:57 changed width to @content_cols since data not printing # in some cases fully when ansi sequences were present int some line but not in others # lines without ansi were printing less by a few chars. # This was prolly copied from rwindow, where it is okay since its for a specific width def print(string, _width = @content_cols) #return unless visible? w = _width == 0? Ncurses.COLS : _width FFI::NCurses.waddnstr(@pad,string.to_s, w) # changed 2011 dts end def show_colored_chunks(chunks, defcolor = nil, defattr = nil) #return unless visible? chunks.each do |chunk| #|color, chunk, attrib| case chunk when Chunks::Chunk color = chunk.color attrib = chunk.attrib text = chunk.text when Array # for earlier demos that used an array color = chunk[0] attrib = chunk[2] text = chunk[1] end color ||= defcolor attrib ||= defattr || NORMAL #cc, bg = ColorMap.get_colors_for_pair color #$log.debug "XXX: CHUNK textpad #{text}, cp #{color} , attrib #{attrib}. #{cc}, #{bg} " FFI::NCurses.wcolor_set(@pad, color,nil) if color FFI::NCurses.wattron(@pad, attrib) if attrib print(text) FFI::NCurses.wattroff(@pad, attrib) if attrib end end def formatted_text text, fmt require 'rbcurse/core/include/chunk' @formatted_text = text @color_parser = fmt @repaint_required = true # don't know if start is always required. so putting in caller #goto_start #remove_all end # write pad onto window #private def padrefresh top = @window.top left = @window.left sr = @startrow + top sc = @startcol + left retval = FFI::NCurses.prefresh(@pad,@prow,@pcol, sr , sc , @rows + sr , @cols+ sc ); $log.warn "XXX: PADREFRESH #{retval}, #{@prow}, #{@pcol}, #{sr}, #{sc}, #{@rows+sr}, #{@cols+sc}." if retval == -1 # padrefresh can fail if width is greater than NCurses.COLS #FFI::NCurses.prefresh(@pad,@prow,@pcol, @startrow + top, @startcol + left, @rows + @startrow + top, @cols+@startcol + left); end # convenience method to return byte private def key x x.getbyte(0) end # length of longest string in array # This will give a 'wrong' max length if the array has ansi color escape sequences in it # which inc the length but won't be printed. Such lines actually have less length when printed # So in such cases, give more space to the pad. def content_cols longest = @content.max_by(&:length) ## 2013-03-06 - 20:41 crashes here for some reason when man gives error message no man entry return 0 unless longest longest.length end public def repaint ## 2013-03-08 - 21:01 This is the fix to the issue of form callign an event like ? or F1 # which throws up a messagebox which leaves a black rect. We have no place to put a refresh # However, form does call repaint for all objects, so we can do a padref here. Otherwise, # it would get rejected. UNfortunately this may happen more often we want, but we never know # when something pops up on the screen. padrefresh unless @repaint_required return unless @repaint_required if @formatted_text $log.debug "XXX: INSIDE FORMATTED TEXT " l = RubyCurses::Utils.parse_formatted_text(@color_parser, @formatted_text) text(l) @formatted_text = nil end ## moved this line up or else create_p was crashing @window ||= @graphic populate_pad if @_populate_needed #HERE we need to populate once so user can pass a renderer unless @suppress_border if @repaint_all ## XXX im not getting the background color. #@window.print_border_only @top, @left, @height-1, @width, $datacolor clr = get_color $datacolor, @color, @bgcolor #@window.print_border @top, @left, @height-1, @width, clr @window.print_border_only @top, @left, @height-1, @width, clr print_title @window.wrefresh end end padrefresh Ncurses::Panel.update_panels @repaint_required = false @repaint_all = false end # # key mappings # def map_keys @mapped_keys = true bind_key([?g,?g], 'goto_start'){ goto_start } # mapping double keys like vim bind_key(279, 'goto_start'){ goto_start } bind_keys([?G,277], 'goto end'){ goto_end } bind_keys([?k,KEY_UP], "Up"){ up } bind_keys([?j,KEY_DOWN], "Down"){ down } bind_key(?\C-e, "Scroll Window Down"){ scroll_window_down } bind_key(?\C-y, "Scroll Window Up"){ scroll_window_up } bind_keys([32,338, ?\C-d], "Scroll Forward"){ scroll_forward } bind_keys([?\C-b,339]){ scroll_backward } # the next one invalidates the single-quote binding for bookmarks #bind_key([?',?']){ goto_last_position } # vim , goto last row position (not column) bind_key(?/, :ask_search) bind_key(?n, :find_more) bind_key([?\C-x, ?>], :scroll_right) bind_key([?\C-x, ?<], :scroll_left) bind_key(?\M-l, :scroll_right) bind_key(?\M-h, :scroll_left) bind_key(?L, :bottom_of_window) bind_key(?M, :middle_of_window) bind_key(?H, :top_of_window) bind_key(?w, :forward_word) bind_key(KEY_ENTER, :fire_action_event) end # goto first line of file def goto_start #@oldindex = @current_index $multiplier ||= 0 if $multiplier > 0 goto_line $multiplier - 1 return end @current_index = 0 @curpos = @pcol = @prow = 0 @prow = 0 $multiplier = 0 end # goto last line of file def goto_end #@oldindex = @current_index $multiplier ||= 0 if $multiplier > 0 goto_line $multiplier - 1 return end @current_index = @content.count() - 1 @prow = @current_index - @scrollatrows $multiplier = 0 end def goto_line line ## we may need to calculate page, zfm style and place at right position for ensure visible #line -= 1 @current_index = line ensure_visible line bounds_check $multiplier = 0 end def top_of_window @current_index = @prow $multiplier ||= 0 if $multiplier > 0 @current_index += $multiplier $multiplier = 0 end end def bottom_of_window @current_index = @prow + @scrollatrows $multiplier ||= 0 if $multiplier > 0 @current_index -= $multiplier $multiplier = 0 end end def middle_of_window @current_index = @prow + (@scrollatrows/2) $multiplier = 0 end # move down a line mimicking vim's j key # @param [int] multiplier entered prior to invoking key def down num=(($multiplier.nil? or $multiplier == 0) ? 1 : $multiplier) #@oldindex = @current_index if num > 10 @current_index += num ensure_visible $multiplier = 0 end # move up a line mimicking vim's k key # @param [int] multiplier entered prior to invoking key def up num=(($multiplier.nil? or $multiplier == 0) ? 1 : $multiplier) #@oldindex = @current_index if num > 10 @current_index -= num #unless is_visible? @current_index #if @prow > @current_index ##$status_message.value = "1 #{@prow} > #{@current_index} " #@prow -= 1 #else #end #end $multiplier = 0 end # scrolls window down mimicking vim C-e # @param [int] multiplier entered prior to invoking key def scroll_window_down num=(($multiplier.nil? or $multiplier == 0) ? 1 : $multiplier) @prow += num if @prow > @current_index @current_index += 1 end #check_prow $multiplier = 0 end # scrolls window up mimicking vim C-y # @param [int] multiplier entered prior to invoking key def scroll_window_up num=(($multiplier.nil? or $multiplier == 0) ? 1 : $multiplier) @prow -= num unless is_visible? @current_index # one more check may be needed here TODO @current_index -= num end $multiplier = 0 end # scrolls lines a window full at a time, on pressing ENTER or C-d or pagedown def scroll_forward #@oldindex = @current_index @current_index += @scrollatrows @prow = @current_index - @scrollatrows end # scrolls lines backward a window full at a time, on pressing pageup # C-u may not work since it is trapped by form earlier. Need to fix def scroll_backward #@oldindex = @current_index @current_index -= @scrollatrows @prow = @current_index - @scrollatrows end def goto_last_position return unless @oldindex tmp = @current_index @current_index = @oldindex @oldindex = tmp bounds_check end def scroll_right # I don't think it will ever be less since we've increased it to cols if @content_cols <= @cols maxpcol = 0 @pcol = 0 else maxpcol = @content_cols - @cols - 1 @pcol += 1 @pcol = maxpcol if @pcol > maxpcol end # to prevent right from retaining earlier painted values # padreader does not do a clear, yet works fine. # OK it has an update_panel after padrefresh, that clears it seems. #this clears entire window not just the pad #FFI::NCurses.wclear(@window.get_window) # so border and title is repainted after window clearing # # Next line was causing all sorts of problems when scrolling with ansi formatted text #@repaint_all = true end def scroll_left @pcol -= 1 end # # # # NOTE : if advancing pcol one has to clear the pad or something or else # there'll be older content on the right side. # def handle_key ch return :UNHANDLED unless @content map_keys unless @mapped_keys @maxrow = @content_rows - @rows @maxcol = @content_cols - @cols # need to understand the above line, can go below zero. # all this seems to work fine in padreader.rb in util. # somehow maxcol going to -33 @oldrow = @prow @oldcol = @pcol $log.debug "XXX: PAD got #{ch} prow = #{@prow}" begin case ch when key(?l) # TODO take multipler #@pcol += 1 if @curpos < @cols @curpos += 1 end when key(?$) #@pcol = @maxcol - 1 @curpos = [@content[@current_index].size, @cols].min when key(?h) # TODO take multipler if @curpos > 0 @curpos -= 1 end #when key(?0) #@curpos = 0 when ?0.getbyte(0)..?9.getbyte(0) if ch == ?0.getbyte(0) && $multiplier == 0 # copy of C-a - start of line @repaint_required = true if @pcol > 0 # tried other things but did not work @pcol = 0 @curpos = 0 return 0 end # storing digits entered so we can multiply motion actions $multiplier *= 10 ; $multiplier += (ch-48) return 0 when ?\C-c.getbyte(0) $multiplier = 0 return 0 else # check for bindings, these cannot override above keys since placed at end begin ret = process_key ch, self $multiplier = 0 bounds_check ## If i press C-x > i get an alert from rwidgets which blacks the screen # if i put a padrefresh here it becomes okay but only for one pad, # i still need to do it for all pads. rescue => err $log.error " TEXTPAD ERROR INS #{err} " $log.debug(err.backtrace.join("\n")) textdialog ["Error in TextPad: #{err} ", *err.backtrace], :title => "Exception" end ## NOTE if textpad does not handle the event and it goes to form which pops # up a messagebox, then padrefresh does not happen, since control does not # come back here, so a black rect is left on screen # please note that a bounds check will not happen for stuff that # is triggered by form, so you'll have to to it yourself or # call setrowcol explicity if the cursor is not updated return :UNHANDLED if ret == :UNHANDLED end rescue => err $log.error " TEXTPAD ERROR 111 #{err} " $log.debug( err) if err $log.debug(err.backtrace.join("\n")) if err textdialog ["Error in TextPad: #{err} ", *err.backtrace], :title => "Exception" $error_message.value = "" ensure padrefresh Ncurses::Panel.update_panels end return 0 end # while loop def fire_action_event return if @content.nil? || @content.size == 0 require 'rbcurse/core/include/ractionevent' aev = TextActionEvent.new self, :PRESS, current_value().to_s, @current_index, @curpos fire_handler :PRESS, aev end def current_value @content[@current_index] end # def on_enter_row arow return if @content.nil? || @content.size == 0 require 'rbcurse/core/include/ractionevent' aev = TextActionEvent.new self, :ENTER_ROW, current_value().to_s, @current_index, @curpos fire_handler :ENTER_ROW, aev @repaint_required = true end # destroy the pad, this needs to be called from somewhere, like when the app # closes or the current window closes , or else we could have a seg fault # or some ugliness on the screen below this one (if nested). # Now since we use get_pad from window, upon the window being destroyed, # it will call this. Else it will destroy pad def destroy FFI::NCurses.delwin(@pad) if @pad # when do i do this ? FIXME @pad = nil end def is_visible? index j = index - @prow #@toprow j >= 0 && j <= @scrollatrows end def on_enter set_form_row end def set_form_row setrowcol @lastrow, @lastcol end def set_form_col end private # check that current_index and prow are within correct ranges # sets row (and someday col too) # sets repaint_required def bounds_check r,c = rowcol @current_index = 0 if @current_index < 0 @current_index = @content.count()-1 if @current_index > @content.count()-1 ensure_visible #$status_message.value = "visible #{@prow} , #{@current_index} " #unless is_visible? @current_index #if @prow > @current_index ##$status_message.value = "1 #{@prow} > #{@current_index} " #@prow -= 1 #else #end #end #end check_prow #$log.debug "XXX: PAD BOUNDS ci:#{@current_index} , old #{@oldrow},pr #{@prow}, max #{@maxrow} pcol #{@pcol} maxcol #{@maxcol}" @crow = @current_index + r - @prow @crow = r if @crow < r # 2 depends on whetehr suppressborders @crow = @row + @height -2 if @crow >= r + @height -2 setrowcol @crow, @curpos+c lastcurpos @crow, @curpos+c if @oldindex != @current_index on_enter_row @current_index @oldindex = @current_index end if @oldrow != @prow || @oldcol != @pcol # only if scrolling has happened. @repaint_required = true end end def lastcurpos r,c @lastrow = r @lastcol = c end # check that prow and pcol are within bounds def check_prow @prow = 0 if @prow < 0 @pcol = 0 if @pcol < 0 cc = @content.count if cc < @rows @prow = 0 else maxrow = cc - @rows - 1 if @prow > maxrow @prow = maxrow end end # we still need to check the max that prow can go otherwise # the pad shows earlier stuff. # return # the following was causing bugs if content was smaller than pad if @prow > @maxrow-1 @prow = @maxrow-1 end if @pcol > @maxcol-1 @pcol = @maxcol-1 end end public ## # Ask user for string to search for def ask_search str = get_string("Enter pattern: ") return if str.nil? str = @last_regex if str == "" return if str == "" ix = next_match str return unless ix @last_regex = str #@oldindex = @current_index @current_index = ix[0] @curpos = ix[1] ensure_visible end ## # Find next matching row for string accepted in ask_search # def find_more return unless @last_regex ix = next_match @last_regex return unless ix #@oldindex = @current_index @current_index = ix[0] @curpos = ix[1] ensure_visible end ## # Find the next row that contains given string # @return row and col offset of match, or nil # @param String to find def next_match str first = nil ## content can be string or Chunkline, so we had to write <tt>index</tt> for this. ## =~ does not give an error, but it does not work. @content.each_with_index do |line, ix| col = line.index str if col first ||= [ ix, col ] if ix > @current_index return [ix, col] end end end return first end ## # Ensure current row is visible, if not make it first row # NOTE - need to check if its at end and then reduce scroll at rows, check_prow does that # # @param current_index (default if not given) # def ensure_visible row = @current_index unless is_visible? row @prow = @current_index end end def forward_word $multiplier = 1 if !$multiplier || $multiplier == 0 line = @current_index buff = @content[line].to_s return unless buff pos = @curpos || 0 # list does not have curpos $multiplier.times { found = buff.index(/[[:punct:][:space:]]\w/, pos) if !found # if not found, we've lost a counter if line+1 < @content.length line += 1 else return end pos = 0 else pos = found + 1 end $log.debug " forward_word: pos #{pos} line #{line} buff: #{buff}" } $multiplier = 0 @current_index = line @curpos = pos ensure_visible #@buffer = @list[@current_index].to_s #set_form_row #set_form_col pos @repaint_required = true end end # class textpad # a test renderer to see how things go class DefaultFileRenderer def render pad, lineno, text bg = :black fg = :white att = NORMAL #cp = $datacolor cp = get_color($datacolor, fg, bg) if text =~ /^\s*# / || text =~ /^\s*## / fg = :red #att = BOLD cp = get_color($datacolor, fg, bg) elsif text =~ /^\s*#/ fg = :blue cp = get_color($datacolor, fg, bg) elsif text =~ /^\s*(class|module) / fg = :cyan att = BOLD cp = get_color($datacolor, fg, bg) elsif text =~ /^\s*def / || text =~ /^\s*function / fg = :yellow att = BOLD cp = get_color($datacolor, fg, bg) elsif text =~ /^\s*(end|if |elsif|else|begin|rescue|ensure|include|extend|while|unless|case |when )/ fg = :magenta att = BOLD cp = get_color($datacolor, fg, bg) elsif text =~ /^\s*=/ # rdoc case fg = :blue bg = :white cp = get_color($datacolor, fg, bg) att = REVERSE end FFI::NCurses.wattron(pad,FFI::NCurses.COLOR_PAIR(cp) | att) FFI::NCurses.mvwaddstr(pad, lineno, 0, text) FFI::NCurses.wattroff(pad,FFI::NCurses.COLOR_PAIR(cp) | att) end end end comment added #!/usr/bin/env ruby # ----------------------------------------------------------------------------- # # File: textpad.rb # Description: A class that displays text using a pad. # The motivation for this is to put formatted text and not care about truncating and # stuff. Also, there will be only one write, not each time scrolling happens. # I found textview code for repaint being more complex than required. # Author: rkumar http://github.com/rkumar/mancurses/ # Date: 2011-11-09 - 16:59 # License: Same as Ruby's License (http://www.ruby-lang.org/LICENSE.txt) # Last update: 2013-03-16 17:41 # # == CHANGES # == TODO # _ in popup case allowing scrolling when it should not so you get an extra char at end # _ The list one needs a f-char like functionality. # x handle putting data again and overwriting existing # When reputting data, the underlying pad needs to be properly cleared # esp last row and last col # # x add mappings and process key in handle_keys and other widget things # - can pad movement and other ops be abstracted into module for reuse # / get scrolling like in vim (C-f e y b d) # # == TODO 2013-03-07 - 20:34 # _ key bindings not showing up -- bind properly # ----------------------------------------------------------------------------- # # require 'rbcurse' require 'rbcurse/core/include/bordertitle' include RubyCurses module Cygnus extend self class TextPad < Widget include BorderTitle dsl_accessor :suppress_border attr_reader :current_index attr_reader :rows , :cols # You may pass height, width, row and col for creating a window otherwise a fullscreen window # will be created. If you pass a window from caller then that window will be used. # Some keys are trapped, jkhl space, pgup, pgdown, end, home, t b # This is currently very minimal and was created to get me started to integrating # pads into other classes such as textview. def initialize form=nil, config={}, &block @editable = false @focusable = true @config = config @row = @col = 0 @prow = @pcol = 0 @startrow = 0 @startcol = 0 @list = [] super ## NOTE # --------------------------------------------------- # Since we are using pads, you need to get your height, width and rows correct # Make sure the height factors in the row, else nothing may show # --------------------------------------------------- #@height = @height.ifzero(FFI::NCurses.LINES) #@width = @width.ifzero(FFI::NCurses.COLS) @rows = @height @cols = @width # NOTE XXX if cols is > COLS then padrefresh can fail @startrow = @row @startcol = @col #@suppress_border = config[:suppress_border] @row_offset = @col_offset = 1 unless @suppress_border @startrow += 1 @startcol += 1 @rows -=3 # 3 is since print_border_only reduces one from width, to check whether this is correct @cols -=3 else # seeing why nothing is printing @rows -=0 # 3 is since print_border_only reduces one from width, to check whether this is correct ## if next is 0 then padrefresh doesn't print @cols -=1 end @row_offset = @col_offset = 0 if @suppress_borders @top = @row @left = @col @lastrow = @row + 1 @lastcol = @col + 1 @_events << :PRESS @_events << :ENTER_ROW @scrollatrows = @height - 3 init_vars end def init_vars $multiplier = 0 @oldindex = @current_index = 0 # column cursor @prow = @pcol = @curpos = 0 if @row && @col @lastrow = @row + 1 @lastcol = @col + 1 end @repaint_required = true end def rowcol #:nodoc: return @row+@row_offset, @col+@col_offset end private ## XXX in list text returns the selected row, list returns the full thing, keep consistent def create_pad destroy if @pad #@pad = FFI::NCurses.newpad(@content_rows, @content_cols) @pad = @window.get_pad(@content_rows, @content_cols ) end private # create and populate pad def populate_pad @_populate_needed = false # how can we make this more sensible ? FIXME #@renderer ||= DefaultFileRenderer.new #if ".rb" == @filetype @content_rows = @content.count @content_cols = content_cols() # this should be explicit and not "intelligent" #@title += " [ #{@content_rows},#{@content_cols}] " if @cols > 50 @content_rows = @rows if @content_rows < @rows @content_cols = @cols if @content_cols < @cols #$log.debug "XXXX content_cols = #{@content_cols}" create_pad # clearstring is the string required to clear the pad to backgroud color @clearstring = nil cp = get_color($datacolor, @color, @bgcolor) @cp = FFI::NCurses.COLOR_PAIR(cp) if cp != $datacolor @clearstring ||= " " * @width end Ncurses::Panel.update_panels @content.each_index { |ix| #FFI::NCurses.mvwaddstr(@pad,ix, 0, @content[ix]) render @pad, ix, @content[ix] } end public # supply a custom renderer that implements +render()+ # @see render def renderer r @renderer = r end # # default method for rendering a line # def render pad, lineno, text if text.is_a? Chunks::ChunkLine FFI::NCurses.wmove @pad, lineno, 0 a = get_attrib @attrib show_colored_chunks text, nil, a return end if @renderer @renderer.render @pad, lineno, text else ## messabox does have a method to paint the whole window in bg color its in rwidget.rb att = NORMAL FFI::NCurses.wattron(@pad, @cp | att) FFI::NCurses.mvwaddstr(@pad,lineno, 0, @clearstring) if @clearstring FFI::NCurses.mvwaddstr(@pad,lineno, 0, @content[lineno]) #FFI::NCurses.mvwaddstr(pad, lineno, 0, text) FFI::NCurses.wattroff(@pad, @cp | att) end end # supply a filename as source for textpad # Reads up file into @content def filename(filename) @file = filename unless File.exists? filename alert "#{filename} does not exist" return end @filetype = File.extname filename @content = File.open(filename,"r").readlines if @filetype == "" if @content.first.index("ruby") @filetype = ".rb" end end init_vars @repaint_all = true @_populate_needed = true end # Supply an array of string to be displayed # This will replace existing text ## XXX in list text returns the selected row, list returns the full thing, keep consistent def text lines raise "text() receiving null content" unless lines @content = lines @_populate_needed = true @repaint_all = true init_vars end alias :list :text def content raise "content is nil " unless @content return @content end ## ---- the next 2 methods deal with printing chunks # we should put it int a common module and include it # in Window and Pad stuff and perhaps include it conditionally. ## 2013-03-07 - 19:57 changed width to @content_cols since data not printing # in some cases fully when ansi sequences were present int some line but not in others # lines without ansi were printing less by a few chars. # This was prolly copied from rwindow, where it is okay since its for a specific width def print(string, _width = @content_cols) #return unless visible? w = _width == 0? Ncurses.COLS : _width FFI::NCurses.waddnstr(@pad,string.to_s, w) # changed 2011 dts end def show_colored_chunks(chunks, defcolor = nil, defattr = nil) #return unless visible? chunks.each do |chunk| #|color, chunk, attrib| case chunk when Chunks::Chunk color = chunk.color attrib = chunk.attrib text = chunk.text when Array # for earlier demos that used an array color = chunk[0] attrib = chunk[2] text = chunk[1] end color ||= defcolor attrib ||= defattr || NORMAL #cc, bg = ColorMap.get_colors_for_pair color #$log.debug "XXX: CHUNK textpad #{text}, cp #{color} , attrib #{attrib}. #{cc}, #{bg} " FFI::NCurses.wcolor_set(@pad, color,nil) if color FFI::NCurses.wattron(@pad, attrib) if attrib print(text) FFI::NCurses.wattroff(@pad, attrib) if attrib end end def formatted_text text, fmt require 'rbcurse/core/include/chunk' @formatted_text = text @color_parser = fmt @repaint_required = true # don't know if start is always required. so putting in caller #goto_start #remove_all end # write pad onto window #private def padrefresh top = @window.top left = @window.left sr = @startrow + top sc = @startcol + left retval = FFI::NCurses.prefresh(@pad,@prow,@pcol, sr , sc , @rows + sr , @cols+ sc ); $log.warn "XXX: PADREFRESH #{retval}, #{@prow}, #{@pcol}, #{sr}, #{sc}, #{@rows+sr}, #{@cols+sc}." if retval == -1 # padrefresh can fail if width is greater than NCurses.COLS #FFI::NCurses.prefresh(@pad,@prow,@pcol, @startrow + top, @startcol + left, @rows + @startrow + top, @cols+@startcol + left); end # convenience method to return byte private def key x x.getbyte(0) end # length of longest string in array # This will give a 'wrong' max length if the array has ansi color escape sequences in it # which inc the length but won't be printed. Such lines actually have less length when printed # So in such cases, give more space to the pad. def content_cols longest = @content.max_by(&:length) ## 2013-03-06 - 20:41 crashes here for some reason when man gives error message no man entry return 0 unless longest longest.length end public def repaint ## 2013-03-08 - 21:01 This is the fix to the issue of form callign an event like ? or F1 # which throws up a messagebox which leaves a black rect. We have no place to put a refresh # However, form does call repaint for all objects, so we can do a padref here. Otherwise, # it would get rejected. UNfortunately this may happen more often we want, but we never know # when something pops up on the screen. padrefresh unless @repaint_required return unless @repaint_required if @formatted_text $log.debug "XXX: INSIDE FORMATTED TEXT " l = RubyCurses::Utils.parse_formatted_text(@color_parser, @formatted_text) text(l) @formatted_text = nil end ## moved this line up or else create_p was crashing @window ||= @graphic populate_pad if @_populate_needed #HERE we need to populate once so user can pass a renderer unless @suppress_border if @repaint_all ## XXX im not getting the background color. #@window.print_border_only @top, @left, @height-1, @width, $datacolor clr = get_color $datacolor, @color, @bgcolor #@window.print_border @top, @left, @height-1, @width, clr @window.print_border_only @top, @left, @height-1, @width, clr print_title @window.wrefresh end end padrefresh Ncurses::Panel.update_panels @repaint_required = false @repaint_all = false end # # key mappings # def map_keys @mapped_keys = true bind_key([?g,?g], 'goto_start'){ goto_start } # mapping double keys like vim bind_key(279, 'goto_start'){ goto_start } bind_keys([?G,277], 'goto end'){ goto_end } bind_keys([?k,KEY_UP], "Up"){ up } bind_keys([?j,KEY_DOWN], "Down"){ down } bind_key(?\C-e, "Scroll Window Down"){ scroll_window_down } bind_key(?\C-y, "Scroll Window Up"){ scroll_window_up } bind_keys([32,338, ?\C-d], "Scroll Forward"){ scroll_forward } bind_keys([?\C-b,339]){ scroll_backward } # the next one invalidates the single-quote binding for bookmarks #bind_key([?',?']){ goto_last_position } # vim , goto last row position (not column) bind_key(?/, :ask_search) bind_key(?n, :find_more) bind_key([?\C-x, ?>], :scroll_right) bind_key([?\C-x, ?<], :scroll_left) bind_key(?\M-l, :scroll_right) bind_key(?\M-h, :scroll_left) bind_key(?L, :bottom_of_window) bind_key(?M, :middle_of_window) bind_key(?H, :top_of_window) bind_key(?w, :forward_word) bind_key(KEY_ENTER, :fire_action_event) end # goto first line of file def goto_start #@oldindex = @current_index $multiplier ||= 0 if $multiplier > 0 goto_line $multiplier - 1 return end @current_index = 0 @curpos = @pcol = @prow = 0 @prow = 0 $multiplier = 0 end # goto last line of file def goto_end #@oldindex = @current_index $multiplier ||= 0 if $multiplier > 0 goto_line $multiplier - 1 return end @current_index = @content.count() - 1 @prow = @current_index - @scrollatrows $multiplier = 0 end def goto_line line ## we may need to calculate page, zfm style and place at right position for ensure visible #line -= 1 @current_index = line ensure_visible line bounds_check $multiplier = 0 end def top_of_window @current_index = @prow $multiplier ||= 0 if $multiplier > 0 @current_index += $multiplier $multiplier = 0 end end def bottom_of_window @current_index = @prow + @scrollatrows $multiplier ||= 0 if $multiplier > 0 @current_index -= $multiplier $multiplier = 0 end end def middle_of_window @current_index = @prow + (@scrollatrows/2) $multiplier = 0 end # move down a line mimicking vim's j key # @param [int] multiplier entered prior to invoking key def down num=(($multiplier.nil? or $multiplier == 0) ? 1 : $multiplier) #@oldindex = @current_index if num > 10 @current_index += num ensure_visible $multiplier = 0 end # move up a line mimicking vim's k key # @param [int] multiplier entered prior to invoking key def up num=(($multiplier.nil? or $multiplier == 0) ? 1 : $multiplier) #@oldindex = @current_index if num > 10 @current_index -= num #unless is_visible? @current_index #if @prow > @current_index ##$status_message.value = "1 #{@prow} > #{@current_index} " #@prow -= 1 #else #end #end $multiplier = 0 end # scrolls window down mimicking vim C-e # @param [int] multiplier entered prior to invoking key def scroll_window_down num=(($multiplier.nil? or $multiplier == 0) ? 1 : $multiplier) @prow += num if @prow > @current_index @current_index += 1 end #check_prow $multiplier = 0 end # scrolls window up mimicking vim C-y # @param [int] multiplier entered prior to invoking key def scroll_window_up num=(($multiplier.nil? or $multiplier == 0) ? 1 : $multiplier) @prow -= num unless is_visible? @current_index # one more check may be needed here TODO @current_index -= num end $multiplier = 0 end # scrolls lines a window full at a time, on pressing ENTER or C-d or pagedown def scroll_forward #@oldindex = @current_index @current_index += @scrollatrows @prow = @current_index - @scrollatrows end # scrolls lines backward a window full at a time, on pressing pageup # C-u may not work since it is trapped by form earlier. Need to fix def scroll_backward #@oldindex = @current_index @current_index -= @scrollatrows @prow = @current_index - @scrollatrows end def goto_last_position return unless @oldindex tmp = @current_index @current_index = @oldindex @oldindex = tmp bounds_check end def scroll_right # I don't think it will ever be less since we've increased it to cols if @content_cols <= @cols maxpcol = 0 @pcol = 0 else maxpcol = @content_cols - @cols - 1 @pcol += 1 @pcol = maxpcol if @pcol > maxpcol end # to prevent right from retaining earlier painted values # padreader does not do a clear, yet works fine. # OK it has an update_panel after padrefresh, that clears it seems. #this clears entire window not just the pad #FFI::NCurses.wclear(@window.get_window) # so border and title is repainted after window clearing # # Next line was causing all sorts of problems when scrolling with ansi formatted text #@repaint_all = true end def scroll_left @pcol -= 1 end # # # # NOTE : if advancing pcol one has to clear the pad or something or else # there'll be older content on the right side. # def handle_key ch return :UNHANDLED unless @content map_keys unless @mapped_keys @maxrow = @content_rows - @rows @maxcol = @content_cols - @cols # need to understand the above line, can go below zero. # all this seems to work fine in padreader.rb in util. # somehow maxcol going to -33 @oldrow = @prow @oldcol = @pcol $log.debug "XXX: PAD got #{ch} prow = #{@prow}" begin case ch when key(?l) # TODO take multipler #@pcol += 1 if @curpos < @cols @curpos += 1 end when key(?$) #@pcol = @maxcol - 1 @curpos = [@content[@current_index].size, @cols].min when key(?h) # TODO take multipler if @curpos > 0 @curpos -= 1 end #when key(?0) #@curpos = 0 when ?0.getbyte(0)..?9.getbyte(0) if ch == ?0.getbyte(0) && $multiplier == 0 # copy of C-a - start of line @repaint_required = true if @pcol > 0 # tried other things but did not work @pcol = 0 @curpos = 0 return 0 end # storing digits entered so we can multiply motion actions $multiplier *= 10 ; $multiplier += (ch-48) return 0 when ?\C-c.getbyte(0) $multiplier = 0 return 0 else # check for bindings, these cannot override above keys since placed at end begin ret = process_key ch, self $multiplier = 0 bounds_check ## If i press C-x > i get an alert from rwidgets which blacks the screen # if i put a padrefresh here it becomes okay but only for one pad, # i still need to do it for all pads. rescue => err $log.error " TEXTPAD ERROR INS #{err} " $log.debug(err.backtrace.join("\n")) textdialog ["Error in TextPad: #{err} ", *err.backtrace], :title => "Exception" end ## NOTE if textpad does not handle the event and it goes to form which pops # up a messagebox, then padrefresh does not happen, since control does not # come back here, so a black rect is left on screen # please note that a bounds check will not happen for stuff that # is triggered by form, so you'll have to to it yourself or # call setrowcol explicity if the cursor is not updated return :UNHANDLED if ret == :UNHANDLED end rescue => err $log.error " TEXTPAD ERROR 111 #{err} " $log.debug( err) if err $log.debug(err.backtrace.join("\n")) if err textdialog ["Error in TextPad: #{err} ", *err.backtrace], :title => "Exception" $error_message.value = "" ensure padrefresh Ncurses::Panel.update_panels end return 0 end # while loop def fire_action_event return if @content.nil? || @content.size == 0 require 'rbcurse/core/include/ractionevent' aev = TextActionEvent.new self, :PRESS, current_value().to_s, @current_index, @curpos fire_handler :PRESS, aev end def current_value @content[@current_index] end # def on_enter_row arow return if @content.nil? || @content.size == 0 require 'rbcurse/core/include/ractionevent' aev = TextActionEvent.new self, :ENTER_ROW, current_value().to_s, @current_index, @curpos fire_handler :ENTER_ROW, aev @repaint_required = true end # destroy the pad, this needs to be called from somewhere, like when the app # closes or the current window closes , or else we could have a seg fault # or some ugliness on the screen below this one (if nested). # Now since we use get_pad from window, upon the window being destroyed, # it will call this. Else it will destroy pad def destroy FFI::NCurses.delwin(@pad) if @pad # when do i do this ? FIXME @pad = nil end def is_visible? index j = index - @prow #@toprow j >= 0 && j <= @scrollatrows end def on_enter set_form_row end def set_form_row setrowcol @lastrow, @lastcol end def set_form_col end private # check that current_index and prow are within correct ranges # sets row (and someday col too) # sets repaint_required def bounds_check r,c = rowcol @current_index = 0 if @current_index < 0 @current_index = @content.count()-1 if @current_index > @content.count()-1 ensure_visible #$status_message.value = "visible #{@prow} , #{@current_index} " #unless is_visible? @current_index #if @prow > @current_index ##$status_message.value = "1 #{@prow} > #{@current_index} " #@prow -= 1 #else #end #end #end check_prow #$log.debug "XXX: PAD BOUNDS ci:#{@current_index} , old #{@oldrow},pr #{@prow}, max #{@maxrow} pcol #{@pcol} maxcol #{@maxcol}" @crow = @current_index + r - @prow @crow = r if @crow < r # 2 depends on whetehr suppressborders @crow = @row + @height -2 if @crow >= r + @height -2 setrowcol @crow, @curpos+c lastcurpos @crow, @curpos+c if @oldindex != @current_index on_enter_row @current_index @oldindex = @current_index end if @oldrow != @prow || @oldcol != @pcol # only if scrolling has happened. @repaint_required = true end end def lastcurpos r,c @lastrow = r @lastcol = c end # check that prow and pcol are within bounds def check_prow @prow = 0 if @prow < 0 @pcol = 0 if @pcol < 0 cc = @content.count if cc < @rows @prow = 0 else maxrow = cc - @rows - 1 if @prow > maxrow @prow = maxrow end end # we still need to check the max that prow can go otherwise # the pad shows earlier stuff. # return # the following was causing bugs if content was smaller than pad if @prow > @maxrow-1 @prow = @maxrow-1 end if @pcol > @maxcol-1 @pcol = @maxcol-1 end end public ## # Ask user for string to search for def ask_search str = get_string("Enter pattern: ") return if str.nil? str = @last_regex if str == "" return if str == "" ix = next_match str return unless ix @last_regex = str #@oldindex = @current_index @current_index = ix[0] @curpos = ix[1] ensure_visible end ## # Find next matching row for string accepted in ask_search # def find_more return unless @last_regex ix = next_match @last_regex return unless ix #@oldindex = @current_index @current_index = ix[0] @curpos = ix[1] ensure_visible end ## # Find the next row that contains given string # @return row and col offset of match, or nil # @param String to find def next_match str first = nil ## content can be string or Chunkline, so we had to write <tt>index</tt> for this. ## =~ does not give an error, but it does not work. @content.each_with_index do |line, ix| col = line.index str if col first ||= [ ix, col ] if ix > @current_index return [ix, col] end end end return first end ## # Ensure current row is visible, if not make it first row # NOTE - need to check if its at end and then reduce scroll at rows, check_prow does that # # @param current_index (default if not given) # def ensure_visible row = @current_index unless is_visible? row @prow = @current_index end end def forward_word $multiplier = 1 if !$multiplier || $multiplier == 0 line = @current_index buff = @content[line].to_s return unless buff pos = @curpos || 0 # list does not have curpos $multiplier.times { found = buff.index(/[[:punct:][:space:]]\w/, pos) if !found # if not found, we've lost a counter if line+1 < @content.length line += 1 else return end pos = 0 else pos = found + 1 end $log.debug " forward_word: pos #{pos} line #{line} buff: #{buff}" } $multiplier = 0 @current_index = line @curpos = pos ensure_visible #@buffer = @list[@current_index].to_s #set_form_row #set_form_col pos @repaint_required = true end end # class textpad # a test renderer to see how things go class DefaultFileRenderer def render pad, lineno, text bg = :black fg = :white att = NORMAL #cp = $datacolor cp = get_color($datacolor, fg, bg) ## XXX believe it or not, the next line can give you "invalid byte sequence in UTF-8 # even when processing filename at times. if text =~ /^\s*# / || text =~ /^\s*## / fg = :red #att = BOLD cp = get_color($datacolor, fg, bg) elsif text =~ /^\s*#/ fg = :blue cp = get_color($datacolor, fg, bg) elsif text =~ /^\s*(class|module) / fg = :cyan att = BOLD cp = get_color($datacolor, fg, bg) elsif text =~ /^\s*def / || text =~ /^\s*function / fg = :yellow att = BOLD cp = get_color($datacolor, fg, bg) elsif text =~ /^\s*(end|if |elsif|else|begin|rescue|ensure|include|extend|while|unless|case |when )/ fg = :magenta att = BOLD cp = get_color($datacolor, fg, bg) elsif text =~ /^\s*=/ # rdoc case fg = :blue bg = :white cp = get_color($datacolor, fg, bg) att = REVERSE end FFI::NCurses.wattron(pad,FFI::NCurses.COLOR_PAIR(cp) | att) FFI::NCurses.mvwaddstr(pad, lineno, 0, text) FFI::NCurses.wattroff(pad,FFI::NCurses.COLOR_PAIR(cp) | att) end end end
#!/usr/bin/env ruby -wKU ################################################################### # Build Jamoma ################################################################### # First include the functions in the jamoma lib libdir = "." Dir.chdir libdir # change to libdir so that requires work require "../library/jamomalib" # C74 build library if(ARGV.length == 0) puts "usage: " puts "build.rb <required:configuration> <optional:clean>" exit 0; end configuration = ARGV[0]; if win32? if(configuration == "Development" || configuration == "Debug" ) configuration = "Debug" else if(configuration == "Deployment" || configuration == "Release" ) configuration = "Release" end end end clean = false; @debug = false; if(ARGV.length > 1) if(ARGV[1] != "0" || ARGV[1] != "false") clean = true; end end if(ARGV.length > 2) if(ARGV[2] != "0" || ARGV[2] != "false") @debug = true; end end puts "Building Jamoma DSP" puts "===================================================" puts " configuration: #{configuration}" puts " clean: #{clean}" #puts " debug the build script: #{debug}" puts " " @build_root = "../../Modular/library/externals" @log_root = "../logs" @svn_root = "../../DSP" @fail_array = Array.new @zerolink = false ####### ## SUB ROUTINES ####### def create_logs # set up log files and ensure that the build_root is there `mkdir -p #{@log_root}` if !FileTest.exist?(@log_root) @build_log = File.new("#{@log_root}/DSP_build.log", "w") @build_log.write("MAX BUILD LOG: #{`date`}\n\n") @build_log.flush @error_log = File.new("#{@log_root}/DSP_error.log", "w") @error_log.write("MAX BUILD ERROR LOG: #{`date`}\n\n") @error_log.flush trap("SIGINT") { die } end def die close_logs exit 0 end def close_logs @build_log.close @error_log.close end def log_build(str) @build_log.write(str) @build_log.write("\n\n") @build_log.flush end def log_error(str) @error_log.write(str) @error_log.write("\n\n") @error_log.flush end def zero_count @cur_total = 0 @cur_count = 0 end def get_count return @cur_total, @cur_count end def copydir(sourcepath, dstpath) out = "" err = "" puts "copy -v #{sourcepath} --> #{dstpath}" Open3.popen3("rm -rf #{dstpath}") do |stdin, stdout, stderr| out = stdout.read err = stderr.read end log_build(out) log_error(err) Open3.popen3("cp -R #{sourcepath} #{dstpath}") do |stdin, stdout, stderr| out = stdout.read err = stderr.read end log_build(out) log_error(err) return 0 end def build_xcode_project(projectdir, projectname, configuration, clean) out = "" err = "" Open3.popen3("nice xcodebuild -project #{projectname} -alltargets -configuration #{configuration} ZERO_LINK=\"NO\" #{"clean" if clean == true} build") do |stdin, stdout, stderr| if(@debug) puts "nice xcodebuild -project #{projectname} -alltargets -configuration #{configuration} ZERO_LINK=\"NO\" #{"clean" if clean == true} build" end out = stdout.read err = stderr.read end if /BUILD SUCCEEDED/.match(out) @cur_count+=1 puts "#{projectname}: BUILD SUCCEEDED" log_build(out) return 1 else @fail_array.push("#{projectdir}/#{projectname}") puts "#{projectname}: BUILD FAILED **************************************" log_error(out) log_error(err) end return 0 end def build_vs_project(projectdir, projectname, configuration, clean) out = "" err = "" Open3.popen3("nice vcbuild.exe #{"/rebuild" if clean == true} \"#{projectname}\" \"#{configuration}\"") do |stdin, stdout, stderr| out = stdout.read err = stderr.read end if /(0 error|up\-to\-date|0 erreur)/.match(out) @cur_count+=1 puts "#{projectname}: BUILD SUCCEEDED" log_build(out) return 1 else @fail_array.push("#{projectdir}/#{projectname}") puts "#{projectname}: BUILD FAILED **************************************" log_error(out) log_error(err) end return 0 end def build_project(projectdir, projectname, configuration, clean) if FileTest.exist?("#{projectdir}/#{projectname}") @cur_total+=1 olddir = Dir.getwd Dir.chdir(projectdir) if win32? @cur_count += build_vs_project(projectdir, projectname, configuration, clean) else @cur_count += build_xcode_project(projectdir, projectname, configuration, clean) end Dir.chdir(olddir) else puts"File Does not exist: #{projectdir}/#{projectname}" end end def find_and_build_project(projectdir, configuration, clean) if win32? rgx = /.vcproj$/ else rgx = /.xcodeproj$/ end Dir.foreach(projectdir) do |file| if rgx.match(file) build_project(projectdir, file, configuration, clean) end end end def build_dir(dir, configuration, clean) dir = "#{@svn_root}/#{dir}" return if !FileTest.exist?(dir) || !FileTest.directory?(dir) Dir.foreach(dir) do |subf| next if /^\./.match(subf) next if /common/.match(subf) next if !FileTest.directory?("#{dir}/#{subf}") find_and_build_project("#{dir}/#{subf}", configuration, clean) end end ################################################################### # CREATE LOG FILES AND RESET COUNTERS ################################################################### create_logs zero_count ################################################################### # FRAMEWORK ################################################################### puts "Building Frameworks..." zero_count if win32? build_project("#{@svn_root}/library", "JamomaDSP.vcproj", configuration, true) `cp #{@svn_root}/../DSP/library/#{configuration}/JamomaDSP.dll #{@svn_root}/../Modular/Jamoma/library/externals/JamomaDSP.dll` else build_project("#{@svn_root}/library", "JamomaDSP.xcodeproj", configuration, true) end ex_total, ex_count = get_count puts "" puts "Building Extensions..." zero_count build_dir("extensions", configuration, clean) ex_total, ex_count = get_count if win32? `cp #{@svn_root}/extensions/builds/*.ttdll #{@svn_root}/../Modular/Jamoma/library/externals/TTBlueExtensions/` end puts "" ################################################################### # EXTERNALS ################################################################### puts "Building Max Externals..." zero_count build_dir("examples/MaxMSP", configuration, clean) ex_total, ex_count = get_count extension = ".mxo" if win32? extension = ".mxe" end src_folder = "Build_Mac" if win32? src_folder = "MaxMSP/builds" end dst_folder = "mac" if win32? dst_folder = "windows" end puts "" if("#{configuration}" == "Development") puts "copying Development" copydir("#{@svn_root}/examples/#{src_folder}/tt.balance~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.balance~#{extension}") copydir("#{@svn_root}/examples/#{src_folder}/tt.dcblock~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.dcblock~#{extension}") copydir("#{@svn_root}/examples/#{src_folder}/tt.degrade~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.degrade~#{extension}") copydir("#{@svn_root}/examples/#{src_folder}/tt.filter~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.filter~#{extension}") copydir("#{@svn_root}/examples/#{src_folder}/tt.gain~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.gain~#{extension}") copydir("#{@svn_root}/examples/#{src_folder}/tt.limiter~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.limiter~#{extension}") copydir("#{@svn_root}/examples/#{src_folder}/tt.overdrive~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.overdrive~#{extension}") copydir("#{@svn_root}/examples/#{src_folder}/tt.ramp~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.ramp~#{extension}") copydir("#{@svn_root}/examples/#{src_folder}/tt.wavetable~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.wavetable~#{extension}") copydir("#{@svn_root}/examples/#{src_folder}/tt.xfade~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.xfade~#{extension}") copydir("#{@svn_root}/examples/#{src_folder}/tt.zerox~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.zerox~#{extension}") else puts "copying Deployment" copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.balance~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.balance~#{extension}") copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.dcblock~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.dcblock~#{extension}") copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.degrade~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.degrade~#{extension}") copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.filter~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.filter~#{extension}") copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.gain~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.gain~#{extension}") copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.limiter~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.limiter~#{extension}") copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.overdrive~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.overdrive~#{extension}") copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.ramp~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.ramp~#{extension}") copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.wavetable~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.wavetable~#{extension}") copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.xfade~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.xfade~#{extension}") copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.zerox~#{extension}", "#{@svn_root}/../Modular/library/externals/#{dst_folder}/tt.zerox~#{extension}") end puts "" puts "copying help files" copydir("#{@svn_root}/examples/MaxMSP/tt.balance~/tt.balance~.maxhelp", "#{@svn_root}/../Modular/documentation/jamoma-help/tt.balance~.maxhelp") copydir("#{@svn_root}/examples/MaxMSP/tt.dcblock~/tt.dcblock~.maxhelp", "#{@svn_root}/../Modular/documentation/jamoma-help/tt.dcblock~.maxhelp") copydir("#{@svn_root}/examples/MaxMSP/tt.degrade~/tt.degrade~.maxhelp", "#{@svn_root}/../Modular/documentation/jamoma-help/tt.degrade~.maxhelp") copydir("#{@svn_root}/examples/MaxMSP/tt.filter~/tt.filter~.maxhelp", "#{@svn_root}/../Modular/documentation/jamoma-help/tt.filter~.maxhelp") copydir("#{@svn_root}/examples/MaxMSP/tt.gain~/tt.gain~.maxhelp", "#{@svn_root}/../Modular/documentation/jamoma-help/tt.gain~.maxhelp") copydir("#{@svn_root}/examples/MaxMSP/tt.limiter~/tt.limiter~.maxhelp", "#{@svn_root}/../Modular/documentation/jamoma-help/tt.limiter~.maxhelp") copydir("#{@svn_root}/examples/MaxMSP/tt.overdrive~/tt.overdrive~.maxhelp", "#{@svn_root}/../Modular/documentation/jamoma-help/tt.overdrive~.maxhelp") copydir("#{@svn_root}/examples/MaxMSP/tt.ramp~/tt.ramp~.maxhelp", "#{@svn_root}/../Modular/documentation/jamoma-help/tt.ramp~.maxhelp") copydir("#{@svn_root}/examples/MaxMSP/tt.wavetable~/tt.wavetable~.maxhelp", "#{@svn_root}/../Modular/documentation/jamoma-help/tt.wavetable~.maxhelp") copydir("#{@svn_root}/examples/MaxMSP/tt.xfade~/tt.xfade~.maxhelp", "#{@svn_root}/../Modular/documentation/jamoma-help/tt.xfade~.maxhelp") copydir("#{@svn_root}/examples/MaxMSP/tt.zerox~/tt.zerox~.maxhelp", "#{@svn_root}/../Modular/documentation/jamoma-help/tt.zerox~.maxhelp") puts "" ################################################################### # FINISH UP ################################################################### puts "=================DONE====================" puts "\nFailed projects:" if @fail_array.length > 0 @fail_array.each do |loser| puts loser end ################################################################### # CLOSE LOG FILES ################################################################### close_logs puts "" exit 0; fixes for copying stage -- folder paths were previously not quite right git-svn-id: e12ca7aaa90aa1d10375b19c0ace38986040f22a@16 cf56d150-baf5-11dd-bdb3-db5ec97ac920 #!/usr/bin/env ruby -wKU ################################################################### # Build Jamoma ################################################################### # First include the functions in the jamoma lib libdir = "." Dir.chdir libdir # change to libdir so that requires work require "../library/jamomalib" # C74 build library if(ARGV.length == 0) puts "usage: " puts "build.rb <required:configuration> <optional:clean>" exit 0; end configuration = ARGV[0]; if win32? if(configuration == "Development" || configuration == "Debug" ) configuration = "Debug" else if(configuration == "Deployment" || configuration == "Release" ) configuration = "Release" end end end clean = false; @debug = false; if(ARGV.length > 1) if(ARGV[1] != "0" || ARGV[1] != "false") clean = true; end end if(ARGV.length > 2) if(ARGV[2] != "0" || ARGV[2] != "false") @debug = true; end end puts "Building Jamoma DSP" puts "===================================================" puts " configuration: #{configuration}" puts " clean: #{clean}" #puts " debug the build script: #{debug}" puts " " @build_root = "../../Modular/library/externals" @log_root = "../logs" @svn_root = "../../DSP" @fail_array = Array.new @zerolink = false ####### ## SUB ROUTINES ####### def create_logs # set up log files and ensure that the build_root is there `mkdir -p #{@log_root}` if !FileTest.exist?(@log_root) @build_log = File.new("#{@log_root}/DSP_build.log", "w") @build_log.write("MAX BUILD LOG: #{`date`}\n\n") @build_log.flush @error_log = File.new("#{@log_root}/DSP_error.log", "w") @error_log.write("MAX BUILD ERROR LOG: #{`date`}\n\n") @error_log.flush trap("SIGINT") { die } end def die close_logs exit 0 end def close_logs @build_log.close @error_log.close end def log_build(str) @build_log.write(str) @build_log.write("\n\n") @build_log.flush end def log_error(str) @error_log.write(str) @error_log.write("\n\n") @error_log.flush end def zero_count @cur_total = 0 @cur_count = 0 end def get_count return @cur_total, @cur_count end def copydir(sourcepath, dstpath) out = "" err = "" puts "copy -v #{sourcepath} --> #{dstpath}" Open3.popen3("rm -rf #{dstpath}") do |stdin, stdout, stderr| out = stdout.read err = stderr.read end log_build(out) log_error(err) Open3.popen3("cp -R #{sourcepath} #{dstpath}") do |stdin, stdout, stderr| out = stdout.read err = stderr.read end log_build(out) log_error(err) return 0 end def build_xcode_project(projectdir, projectname, configuration, clean) out = "" err = "" Open3.popen3("nice xcodebuild -project #{projectname} -alltargets -configuration #{configuration} ZERO_LINK=\"NO\" #{"clean" if clean == true} build") do |stdin, stdout, stderr| if(@debug) puts "nice xcodebuild -project #{projectname} -alltargets -configuration #{configuration} ZERO_LINK=\"NO\" #{"clean" if clean == true} build" end out = stdout.read err = stderr.read end if /BUILD SUCCEEDED/.match(out) @cur_count+=1 puts "#{projectname}: BUILD SUCCEEDED" log_build(out) return 1 else @fail_array.push("#{projectdir}/#{projectname}") puts "#{projectname}: BUILD FAILED **************************************" log_error(out) log_error(err) end return 0 end def build_vs_project(projectdir, projectname, configuration, clean) out = "" err = "" Open3.popen3("nice vcbuild.exe #{"/rebuild" if clean == true} \"#{projectname}\" \"#{configuration}\"") do |stdin, stdout, stderr| out = stdout.read err = stderr.read end if /(0 error|up\-to\-date|0 erreur)/.match(out) @cur_count+=1 puts "#{projectname}: BUILD SUCCEEDED" log_build(out) return 1 else @fail_array.push("#{projectdir}/#{projectname}") puts "#{projectname}: BUILD FAILED **************************************" log_error(out) log_error(err) end return 0 end def build_project(projectdir, projectname, configuration, clean) if FileTest.exist?("#{projectdir}/#{projectname}") @cur_total+=1 olddir = Dir.getwd Dir.chdir(projectdir) if win32? @cur_count += build_vs_project(projectdir, projectname, configuration, clean) else @cur_count += build_xcode_project(projectdir, projectname, configuration, clean) end Dir.chdir(olddir) else puts"File Does not exist: #{projectdir}/#{projectname}" end end def find_and_build_project(projectdir, configuration, clean) if win32? rgx = /.vcproj$/ else rgx = /.xcodeproj$/ end Dir.foreach(projectdir) do |file| if rgx.match(file) build_project(projectdir, file, configuration, clean) end end end def build_dir(dir, configuration, clean) dir = "#{@svn_root}/#{dir}" return if !FileTest.exist?(dir) || !FileTest.directory?(dir) Dir.foreach(dir) do |subf| next if /^\./.match(subf) next if /common/.match(subf) next if !FileTest.directory?("#{dir}/#{subf}") find_and_build_project("#{dir}/#{subf}", configuration, clean) end end ################################################################### # CREATE LOG FILES AND RESET COUNTERS ################################################################### create_logs zero_count ################################################################### # FRAMEWORK ################################################################### puts "Building Frameworks..." zero_count if win32? build_project("#{@svn_root}/library", "JamomaDSP.vcproj", configuration, true) `cp #{@svn_root}/../DSP/library/#{configuration}/JamomaDSP.dll #{@svn_root}/../Modular/Jamoma/library/externals/JamomaDSP.dll` else build_project("#{@svn_root}/library", "JamomaDSP.xcodeproj", configuration, true) end ex_total, ex_count = get_count puts "" puts "Building Extensions..." zero_count build_dir("extensions", configuration, clean) ex_total, ex_count = get_count if win32? `cp #{@svn_root}/extensions/builds/*.ttdll #{@svn_root}/../Modular/Jamoma/library/externals/TTBlueExtensions/` end puts "" ################################################################### # EXTERNALS ################################################################### puts "Building Max Externals..." zero_count build_dir("examples/MaxMSP", configuration, clean) ex_total, ex_count = get_count extension = ".mxo" if win32? extension = ".mxe" end src_folder = "Build_Mac" if win32? src_folder = "MaxMSP/builds" end dst_folder = "mac" if win32? dst_folder = "windows" end puts "" if("#{configuration}" == "Development") puts "copying Development" copydir("#{@svn_root}/examples/#{src_folder}/tt.balance~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.balance~#{extension}") copydir("#{@svn_root}/examples/#{src_folder}/tt.dcblock~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.dcblock~#{extension}") copydir("#{@svn_root}/examples/#{src_folder}/tt.degrade~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.degrade~#{extension}") copydir("#{@svn_root}/examples/#{src_folder}/tt.filter~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.filter~#{extension}") copydir("#{@svn_root}/examples/#{src_folder}/tt.gain~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.gain~#{extension}") copydir("#{@svn_root}/examples/#{src_folder}/tt.limiter~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.limiter~#{extension}") copydir("#{@svn_root}/examples/#{src_folder}/tt.overdrive~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.overdrive~#{extension}") copydir("#{@svn_root}/examples/#{src_folder}/tt.ramp~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.ramp~#{extension}") copydir("#{@svn_root}/examples/#{src_folder}/tt.wavetable~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.wavetable~#{extension}") copydir("#{@svn_root}/examples/#{src_folder}/tt.xfade~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.xfade~#{extension}") copydir("#{@svn_root}/examples/#{src_folder}/tt.zerox~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.zerox~#{extension}") else puts "copying Deployment" copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.balance~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.balance~#{extension}") copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.dcblock~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.dcblock~#{extension}") copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.degrade~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.degrade~#{extension}") copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.filter~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.filter~#{extension}") copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.gain~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.gain~#{extension}") copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.limiter~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.limiter~#{extension}") copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.overdrive~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.overdrive~#{extension}") copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.ramp~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.ramp~#{extension}") copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.wavetable~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.wavetable~#{extension}") copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.xfade~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.xfade~#{extension}") copydir("#{@svn_root}../DSP/examples/#{src_folder}/tt.zerox~#{extension}", "#{@svn_root}/../Modular/Jamoma/library/externals/#{dst_folder}/tt.zerox~#{extension}") end puts "" puts "copying help files" copydir("#{@svn_root}/examples/MaxMSP/tt.balance~/tt.balance~.maxhelp", "#{@svn_root}/../Modular/Jamoma/documentation/jamoma-help/tt.balance~.maxhelp") copydir("#{@svn_root}/examples/MaxMSP/tt.dcblock~/tt.dcblock~.maxhelp", "#{@svn_root}/../Modular/Jamoma/documentation/jamoma-help/tt.dcblock~.maxhelp") copydir("#{@svn_root}/examples/MaxMSP/tt.degrade~/tt.degrade~.maxhelp", "#{@svn_root}/../Modular/Jamoma/documentation/jamoma-help/tt.degrade~.maxhelp") copydir("#{@svn_root}/examples/MaxMSP/tt.filter~/tt.filter~.maxhelp", "#{@svn_root}/../Modular/Jamoma/documentation/jamoma-help/tt.filter~.maxhelp") copydir("#{@svn_root}/examples/MaxMSP/tt.gain~/tt.gain~.maxhelp", "#{@svn_root}/../Modular/Jamoma/documentation/jamoma-help/tt.gain~.maxhelp") copydir("#{@svn_root}/examples/MaxMSP/tt.limiter~/tt.limiter~.maxhelp", "#{@svn_root}/../Modular/Jamoma/documentation/jamoma-help/tt.limiter~.maxhelp") copydir("#{@svn_root}/examples/MaxMSP/tt.overdrive~/tt.overdrive~.maxhelp", "#{@svn_root}/../Modular/Jamoma/documentation/jamoma-help/tt.overdrive~.maxhelp") copydir("#{@svn_root}/examples/MaxMSP/tt.ramp~/tt.ramp~.maxhelp", "#{@svn_root}/../Modular/Jamoma/documentation/jamoma-help/tt.ramp~.maxhelp") copydir("#{@svn_root}/examples/MaxMSP/tt.wavetable~/tt.wavetable~.maxhelp", "#{@svn_root}/../Modular/Jamoma/documentation/jamoma-help/tt.wavetable~.maxhelp") copydir("#{@svn_root}/examples/MaxMSP/tt.xfade~/tt.xfade~.maxhelp", "#{@svn_root}/../Modular/Jamoma/documentation/jamoma-help/tt.xfade~.maxhelp") copydir("#{@svn_root}/examples/MaxMSP/tt.zerox~/tt.zerox~.maxhelp", "#{@svn_root}/../Modular/Jamoma/documentation/jamoma-help/tt.zerox~.maxhelp") puts "" ################################################################### # FINISH UP ################################################################### puts "=================DONE====================" puts "\nFailed projects:" if @fail_array.length > 0 @fail_array.each do |loser| puts loser end ################################################################### # CLOSE LOG FILES ################################################################### close_logs puts "" exit 0;
module DCPU16 VERSION = "0.0.4.beta" end bumped version to 0.0.4.0 module DCPU16 VERSION = "0.0.4.0" end
module DynamoDB VERSION = "0.5.1" end Bump up version module DynamoDB VERSION = "0.5.2" end
require 'capistrano' require 'capistrano/cli' require 'common" Dir.glob(File.join(File.dirname(__FILE__), '/deploy-recipes/*.rb')).sort.each { |f| load f } adding new stuff require 'capistrano' require 'capistrano/cli' require 'common' Dir.glob(File.join(File.dirname(__FILE__), '/deploy-recipes/*.rb')).sort.each { |f| load f }
require 'ostruct' unless OpenStruct.respond_to?(:dig) OpenStruct.class_eval do # # Retrieves the value object corresponding to the each +name+ # objects repeatedly. # # address = OpenStruct.new('city' => "Anytown NC", 'zip' => 12345) # person = OpenStruct.new('name' => 'John Smith', 'address' => address) # person.dig(:address, 'zip') # => 12345 # person.dig(:business_address, 'zip') # => nil # def dig(name, *args) begin name = name.to_sym rescue NoMethodError raise TypeError, "#{name} is not a symbol nor a string" end return nil unless self.respond_to?(name) value = self.send(name) return value if args.length == 0 || value.nil? DigRb.guard_dig(value) value.dig(*args) end end end Update ostruct.rb require 'ostruct' unless OpenStruct.instance_methods.include?(:dig) OpenStruct.class_eval do # # Retrieves the value object corresponding to the each +name+ # objects repeatedly. # # address = OpenStruct.new('city' => "Anytown NC", 'zip' => 12345) # person = OpenStruct.new('name' => 'John Smith', 'address' => address) # person.dig(:address, 'zip') # => 12345 # person.dig(:business_address, 'zip') # => nil # def dig(name, *args) begin name = name.to_sym rescue NoMethodError raise TypeError, "#{name} is not a symbol nor a string" end return nil unless self.respond_to?(name) value = self.send(name) return value if args.length == 0 || value.nil? DigRb.guard_dig(value) value.dig(*args) end end end
class Dir #Note: will not return . and .. def self.deep_entries(dir) dir_regex = /^#{Regexp.escape(dir)}\// Dir.glob("#{dir.gsub(/(\[|\]|\*|\?)/, "\\\\\\1")}/**/*").map { |d| d.sub(dir_regex, '') } end end Finally fix silent failure with importing books with curly brackets in the folder/file name class Dir #Note: will not return . and .. def self.deep_entries(dir) dir_regex = /^#{Regexp.escape(dir)}\// Dir.glob("#{dir.gsub(/(\{|\}|\[|\]|\*|\?)/, "\\\\\\1")}/**/*").map { |d| d.sub(dir_regex, '') } end end
# frozen_string_literal: true # These classes hold relevant Discord data, such as messages or channels. require 'ostruct' require 'discordrb/permissions' require 'discordrb/errors' require 'discordrb/api' require 'discordrb/api/channel' require 'discordrb/api/server' require 'discordrb/api/invite' require 'discordrb/api/user' require 'time' require 'base64' # Discordrb module module Discordrb # The unix timestamp Discord IDs are based on DISCORD_EPOCH = 1_420_070_400_000 # Compares two objects based on IDs - either the objects' IDs are equal, or one object is equal to the other's ID. def self.id_compare(one_id, other) other.respond_to?(:resolve_id) ? (one_id.resolve_id == other.resolve_id) : (one_id == other) end # The maximum length a Discord message can have CHARACTER_LIMIT = 2000 # Splits a message into chunks of 2000 characters. Attempts to split by lines if possible. # @param msg [String] The message to split. # @return [Array<String>] the message split into chunks def self.split_message(msg) # If the messages is empty, return an empty array return [] if msg.empty? # Split the message into lines lines = msg.lines # Turn the message into a "triangle" of consecutively longer slices, for example the array [1,2,3,4] would become # [ # [1], # [1, 2], # [1, 2, 3], # [1, 2, 3, 4] # ] tri = [*0..(lines.length - 1)].map { |i| lines.combination(i + 1).first } # Join the individual elements together to get an array of strings with consecutively more lines joined = tri.map(&:join) # Find the largest element that is still below the character limit, or if none such element exists return the first ideal = joined.max_by { |e| e.length > CHARACTER_LIMIT ? -1 : e.length } # If it's still larger than the character limit (none was smaller than it) split it into slices with the length # being the character limit, otherwise just return an array with one element ideal_ary = ideal.length > CHARACTER_LIMIT ? ideal.chars.each_slice(CHARACTER_LIMIT).map(&:join) : [ideal] # Slice off the ideal part and strip newlines rest = msg[ideal.length..-1].strip # If none remains, return an empty array -> we're done return [] unless rest # Otherwise, call the method recursively to split the rest of the string and add it onto the ideal array ideal_ary + split_message(rest) end # Mixin for objects that have IDs module IDObject # @return [Integer] the ID which uniquely identifies this object across Discord. attr_reader :id alias_method :resolve_id, :id # ID based comparison def ==(other) Discordrb.id_compare(@id, other) end # Estimates the time this object was generated on based on the beginning of the ID. This is fairly accurate but # shouldn't be relied on as Discord might change its algorithm at any time # @return [Time] when this object was created at def creation_time # Milliseconds ms = (@id >> 22) + DISCORD_EPOCH Time.at(ms / 1000.0) end end # Mixin for the attributes users should have module UserAttributes # @return [String] this user's username attr_reader :username alias_method :name, :username # @return [String] this user's discriminator which is used internally to identify users with identical usernames. attr_reader :discriminator alias_method :discrim, :discriminator alias_method :tag, :discriminator alias_method :discord_tag, :discriminator # @return [true, false] whether this user is a Discord bot account attr_reader :bot_account alias_method :bot_account?, :bot_account # @return [String] the ID of this user's current avatar, can be used to generate an avatar URL. # @see #avatar_url attr_reader :avatar_id # Utility function to mention users in messages # @return [String] the mention code in the form of <@id> def mention "<@#{@id}>" end # Utility function to get Discord's distinct representation of a user, i. e. username + discriminator # @return [String] distinct representation of user def distinct "#{@username}##{@discriminator}" end # Utility function to get a user's avatar URL. # @return [String] the URL to the avatar image. def avatar_url API::User.avatar_url(@id, @avatar_id) end end # User on Discord, including internal data like discriminators class User include IDObject include UserAttributes # @!attribute [r] status # @return [Symbol] the current online status of the user (`:online`, `:offline` or `:idle`) attr_accessor :status # @!attribute [r] game # @return [String, nil] the game the user is currently playing, or `nil` if none is being played. attr_accessor :game def initialize(data, bot) @bot = bot @username = data['username'] @id = data['id'].to_i @discriminator = data['discriminator'] @avatar_id = data['avatar'] @roles = {} @bot_account = false @bot_account = true if data['bot'] @status = :offline end # Get a user's PM channel or send them a PM # @overload pm # Creates a private message channel for this user or returns an existing one if it already exists # @return [Channel] the PM channel to this user. # @overload pm(content) # Sends a private to this user. # @param content [String] The content to send. # @return [Message] the message sent to this user. def pm(content = nil) if content # Recursively call pm to get the channel, then send a message to it channel = pm channel.send_message(content) else # If no message was specified, return the PM channel @bot.pm_channel(@id) end end alias_method :dm, :pm # Send the user a file. # @param file [File] The file to send to the user # @param caption [String] The caption of the file being sent # @return [Message] the message sent to this user. def send_file(file, caption = nil) pm.send_file(file, caption: caption) end # Set the user's name # @note for internal use only # @!visibility private def update_username(username) @username = username end # Add an await for a message from this user. Specifically, this adds a global await for a MessageEvent with this # user's ID as a :from attribute. # @see Bot#add_await def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { from: @id }.merge(attributes), &block) end # Gets the member this user is on a server # @param server [Server] The server to get the member for # @return [Member] this user as a member on a particular server def on(server) id = server.resolve_id @bot.server(id).member(@id) end # Is the user the bot? # @return [true, false] whether this user is the bot def current_bot? @bot.profile.id == @id end # @return [true, false] whether this user is a fake user for a webhook message def webhook? @discriminator == Message::ZERO_DISCRIM end [:offline, :idle, :online].each do |e| define_method(e.to_s + '?') do @status.to_sym == e end end # The inspect method is overwritten to give more useful output def inspect "<User username=#{@username} id=#{@id} discriminator=#{@discriminator}>" end end # OAuth Application information class Application include IDObject # @return [String] the application name attr_reader :name # @return [String] the application description attr_reader :description # @return [Array<String>] the applications origins permitted to use RPC attr_reader :rpc_origins # @return [Integer] attr_reader :flags # Gets the user object of the owner. May be limited to username, discriminator, # ID and avatar if the bot cannot reach the owner. # @return [User] the user object of the owner attr_reader :owner def initialize(data, bot) @bot = bot @name = data['name'] @id = data['id'].to_i @description = data['description'] @icon_id = data['icon'] @rpc_origins = data['rpc_origins'] @flags = data['flags'] @owner = @bot.ensure_user(data['owner']) end # Utility function to get a application's icon URL. # @return [String, nil] the URL to the icon image (nil if no image is set). def icon_url return nil if @icon_id.nil? API.app_icon_url(@id, @icon_id) end # The inspect method is overwritten to give more useful output def inspect "<Application name=#{@name} id=#{@id}>" end end # Mixin for the attributes members and private members should have module MemberAttributes # @return [Time] when this member joined the server. attr_reader :joined_at # @return [String, nil] the nickname this member has, or nil if it has none. attr_reader :nick alias_method :nickname, :nick # @return [Array<Role>] the roles this member has. attr_reader :roles # @return [Server] the server this member is on. attr_reader :server end # Mixin to calculate resulting permissions from overrides etc. module PermissionCalculator # Checks whether this user can do the particular action, regardless of whether it has the permission defined, # through for example being the server owner or having the Manage Roles permission # @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list. # @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked. # @example Check if the bot can send messages to a specific channel in a server. # bot_profile = bot.profile.on(event.server) # can_send_messages = bot_profile.permission?(:send_messages, channel) # @return [true, false] whether or not this user has the permission. def permission?(action, channel = nil) # If the member is the server owner, it irrevocably has all permissions. return true if owner? # First, check whether the user has Manage Roles defined. # (Coincidentally, Manage Permissions is the same permission as Manage Roles, and a # Manage Permissions deny overwrite will override Manage Roles, so we can just check for # Manage Roles once and call it a day.) return true if defined_permission?(:administrator, channel) # Otherwise, defer to defined_permission defined_permission?(action, channel) end # Checks whether this user has a particular permission defined (i. e. not implicit, through for example # Manage Roles) # @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list. # @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked. # @example Check if a member has the Manage Channels permission defined in the server. # has_manage_channels = member.defined_permission?(:manage_channels) # @return [true, false] whether or not this user has the permission defined. def defined_permission?(action, channel = nil) # Get the permission the user's roles have role_permission = defined_role_permission?(action, channel) # Once we have checked the role permission, we have to check the channel overrides for the # specific user user_specific_override = permission_overwrite(action, channel, id) # Use the ID reader as members have no ID instance variable # Merge the two permissions - if an override is defined, it has to be allow, otherwise we only care about the role return role_permission unless user_specific_override user_specific_override == :allow end # Define methods for querying permissions Discordrb::Permissions::Flags.each_value do |flag| define_method "can_#{flag}?" do |channel = nil| permission? flag, channel end end alias_method :can_administrate?, :can_administrator? private def defined_role_permission?(action, channel) # For each role, check if # (1) the channel explicitly allows or permits an action for the role and # (2) if the user is allowed to do the action if the channel doesn't specify @roles.reduce(false) do |can_act, role| # Get the override defined for the role on the channel channel_allow = permission_overwrite(action, channel, role.id) can_act = if channel_allow # If the channel has an override, check whether it is an allow - if yes, # the user can act, if not, it can't channel_allow == :allow else # Otherwise defer to the role role.permissions.instance_variable_get("@#{action}") || can_act end can_act end end def permission_overwrite(action, channel, id) # If no overwrites are defined, or no channel is set, no overwrite will be present return nil unless channel && channel.permission_overwrites[id] # Otherwise, check the allow and deny objects allow = channel.permission_overwrites[id].allow deny = channel.permission_overwrites[id].deny if allow.instance_variable_get("@#{action}") :allow elsif deny.instance_variable_get("@#{action}") :deny end # If there's no variable defined, nil will implicitly be returned end end # A voice state represents the state of a member's connection to a voice channel. It includes data like the voice # channel the member is connected to and mute/deaf flags. class VoiceState # @return [Integer] the ID of the user whose voice state is represented by this object. attr_reader :user_id # @return [true, false] whether this voice state's member is muted server-wide. attr_reader :mute # @return [true, false] whether this voice state's member is deafened server-wide. attr_reader :deaf # @return [true, false] whether this voice state's member has muted themselves. attr_reader :self_mute # @return [true, false] whether this voice state's member has deafened themselves. attr_reader :self_deaf # @return [Channel] the voice channel this voice state's member is in. attr_reader :voice_channel # @!visibility private def initialize(user_id) @user_id = user_id end # Update this voice state with new data from Discord # @note For internal use only. # @!visibility private def update(channel, mute, deaf, self_mute, self_deaf) @voice_channel = channel @mute = mute @deaf = deaf @self_mute = self_mute @self_deaf = self_deaf end end # A member is a user on a server. It differs from regular users in that it has roles, voice statuses and things like # that. class Member < DelegateClass(User) # @return [true, false] whether this member is muted server-wide. def mute voice_state_attribute(:mute) end # @return [true, false] whether this member is deafened server-wide. def deaf voice_state_attribute(:deaf) end # @return [true, false] whether this member has muted themselves. def self_mute voice_state_attribute(:self_mute) end # @return [true, false] whether this member has deafened themselves. def self_deaf voice_state_attribute(:self_deaf) end # @return [Channel] the voice channel this member is in. def voice_channel voice_state_attribute(:voice_channel) end alias_method :muted?, :mute alias_method :deafened?, :deaf alias_method :self_muted?, :self_mute alias_method :self_deafened?, :self_deaf include MemberAttributes # @!visibility private def initialize(data, server, bot) @bot = bot @user = bot.ensure_user(data['user']) super @user # Initialize the delegate class # Somehow, Discord doesn't send the server ID in the standard member format... raise ArgumentError, 'Cannot create a member without any information about the server!' if server.nil? && data['guild_id'].nil? @server = server || bot.server(data['guild_id'].to_i) # Initialize the roles by getting the roles from the server one-by-one update_roles(data['roles']) @nick = data['nick'] @joined_at = data['joined_at'] ? Time.parse(data['joined_at']) : nil end # @return [true, false] whether this member is the server owner. def owner? @server.owner == self end # @param role [Role, Integer, #resolve_id] the role to check or its ID. # @return [true, false] whether this member has the specified role. def role?(role) role = role.resolve_id @roles.any? { |e| e.id == role } end # Bulk sets a member's roles. # @param role [Role, Array<Role>] The role(s) to set. def roles=(role) role_ids = role_id_array(role) API::Server.update_member(@bot.token, @server.id, @user.id, roles: role_ids) end # Adds and removes roles from a member. # @param add [Role, Array<Role>] The role(s) to add. # @param remove [Role, Array<Role>] The role(s) to remove. # @example Remove the 'Member' role from a user, and add the 'Muted' role to them. # to_add = server.roles.find {|role| role.name == 'Muted'} # to_remove = server.roles.find {|role| role.name == 'Member'} # member.modify_roles(to_add, to_remove) def modify_roles(add, remove) add_role_ids = role_id_array(add) remove_role_ids = role_id_array(remove) old_role_ids = @roles.map(&:id) new_role_ids = (old_role_ids - remove_role_ids + add_role_ids).uniq API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids) end # Adds one or more roles to this member. # @param role [Role, Array<Role>] The role(s) to add. def add_role(role) role_ids = role_id_array(role) old_role_ids = @roles.map(&:id) new_role_ids = (old_role_ids + role_ids).uniq API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids) end # Removes one or more roles from this member. # @param role [Role, Array<Role>] The role(s) to remove. def remove_role(role) old_role_ids = @roles.map(&:id) role_ids = role_id_array(role) new_role_ids = old_role_ids.reject { |i| role_ids.include?(i) } API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids) end # Server deafens this member. def server_deafen API::Server.update_member(@bot.token, @server.id, @user.id, deaf: true) end # Server undeafens this member. def server_undeafen API::Server.update_member(@bot.token, @server.id, @user.id, deaf: false) end # Server mutes this member. def server_mute API::Server.update_member(@bot.token, @server.id, @user.id, mute: true) end # Server unmutes this member. def server_unmute API::Server.update_member(@bot.token, @server.id, @user.id, mute: false) end # Sets or resets this member's nickname. Requires the Change Nickname permission for the bot itself and Manage # Nicknames for other users. # @param nick [String, nil] The string to set the nickname to, or nil if it should be reset. def nick=(nick) # Discord uses the empty string to signify 'no nickname' so we convert nil into that nick ||= '' if @user.current_bot? API::User.change_own_nickname(@bot.token, @server.id, nick) else API::Server.update_member(@bot.token, @server.id, @user.id, nick: nick) end end alias_method :nickname=, :nick= # @return [String] the name the user displays as (nickname if they have one, username otherwise) def display_name nickname || username end # Update this member's roles # @note For internal use only. # @!visibility private def update_roles(roles) @roles = roles.map do |role| role.is_a?(Role) ? role : @server.role(role.to_i) end end # Update this member's nick # @note For internal use only. # @!visibility private def update_nick(nick) @nick = nick end include PermissionCalculator # Overwriting inspect for debug purposes def inspect "<Member user=#{@user.inspect} server=#{@server.inspect} joined_at=#{@joined_at} roles=#{@roles.inspect} voice_channel=#{@voice_channel.inspect} mute=#{@mute} deaf=#{@deaf} self_mute=#{@self_mute} self_deaf=#{@self_deaf}>" end private # Utility method to get a list of role IDs from one role or an array of roles def role_id_array(role) if role.is_a? Array role.map(&:resolve_id) else [role.resolve_id] end end # Utility method to get data out of this member's voice state def voice_state_attribute(name) voice_state = @server.voice_states[@user.id] voice_state.send name if voice_state end end # Recipients are members on private channels - they exist for completeness purposes, but all # the attributes will be empty. class Recipient < DelegateClass(User) include MemberAttributes # @return [Channel] the private channel this recipient is the recipient of. attr_reader :channel # @!visibility private def initialize(user, channel, bot) @bot = bot @channel = channel raise ArgumentError, 'Tried to create a recipient for a public channel!' unless @channel.private? @user = user super @user # Member attributes @mute = @deaf = @self_mute = @self_deaf = false @voice_channel = nil @server = nil @roles = [] @joined_at = @channel.creation_time end # Overwriting inspect for debug purposes def inspect "<Recipient user=#{@user.inspect} channel=#{@channel.inspect}>" end end # This class is a special variant of User that represents the bot's user profile (things like own username and the avatar). # It can be accessed using {Bot#profile}. class Profile < User def initialize(data, bot) super(data, bot) end # Whether or not the user is the bot. The Profile can only ever be the bot user, so this always returns true. # @return [true] def current_bot? true end # Sets the bot's username. # @param username [String] The new username. def username=(username) update_profile_data(username: username) end alias_method :name=, :username= # Changes the bot's avatar. # @param avatar [String, #read] A JPG file to be used as the avatar, either # something readable (e. g. File Object) or as a data URL. def avatar=(avatar) if avatar.respond_to? :read # Set the file to binary mode if supported, so we don't get problems with Windows avatar.binmode if avatar.respond_to?(:binmode) avatar_string = 'data:image/jpg;base64,' avatar_string += Base64.strict_encode64(avatar.read) update_profile_data(avatar: avatar_string) else update_profile_data(avatar: avatar) end end # Updates the cached profile data with the new one. # @note For internal use only. # @!visibility private def update_data(new_data) @username = new_data[:username] || @username @avatar_id = new_data[:avatar_id] || @avatar_id end # Sets the user status setting to Online. # @note Only usable on User accounts. def online update_profile_status_setting('online') end # Sets the user status setting to Idle. # @note Only usable on User accounts. def idle update_profile_status_setting('idle') end # Sets the user status setting to Do Not Disturb. # @note Only usable on User accounts. def dnd update_profile_status_setting('dnd') end alias_method(:busy, :dnd) # Sets the user status setting to Invisible. # @note Only usable on User accounts. def invisible update_profile_status_setting('invisible') end # The inspect method is overwritten to give more useful output def inspect "<Profile user=#{super}>" end private # Internal handler for updating the user's status setting def update_profile_status_setting(status) API::User.change_status_setting(@bot.token, status) end def update_profile_data(new_data) API::User.update_profile(@bot.token, nil, nil, new_data[:username] || @username, new_data.key?(:avatar) ? new_data[:avatar] : @avatar_id) update_data(new_data) end end # A Discord role that contains permissions and applies to certain users class Role include IDObject # @return [Permissions] this role's permissions. attr_reader :permissions # @return [String] this role's name ("new role" if it hasn't been changed) attr_reader :name # @return [true, false] whether or not this role should be displayed separately from other users attr_reader :hoist # @return [true, false] whether this role can be mentioned using a role mention attr_reader :mentionable alias_method :mentionable?, :mentionable # @return [ColourRGB] the role colour attr_reader :colour alias_method :color, :colour # @return [Integer] the position of this role in the hierarchy attr_reader :position # This class is used internally as a wrapper to a Role object that allows easy writing of permission data. class RoleWriter # @!visibility private def initialize(role, token) @role = role @token = token end # Write the specified permission data to the role, without updating the permission cache # @param bits [Integer] The packed permissions to write. def write(bits) @role.send(:packed=, bits, false) end # The inspect method is overridden, in this case to prevent the token being leaked def inspect "<RoleWriter role=#{@role} token=...>" end end # @!visibility private def initialize(data, bot, server = nil) @bot = bot @server = server @permissions = Permissions.new(data['permissions'], RoleWriter.new(self, @bot.token)) @name = data['name'] @id = data['id'].to_i @position = data['position'] @hoist = data['hoist'] @mentionable = data['mentionable'] @colour = ColourRGB.new(data['color']) end # @return [String] a string that will mention this role, if it is mentionable. def mention "<@&#{@id}>" end # @return [Array<Member>] an array of members who have this role. # @note This requests a member chunk if it hasn't for the server before, which may be slow initially def members @server.members.select { |m| m.role? role } end alias_method :users, :members # Updates the data cache from another Role object # @note For internal use only # @!visibility private def update_from(other) @permissions = other.permissions @name = other.name @hoist = other.hoist @colour = other.colour @position = other.position end # Updates the data cache from a hash containing data # @note For internal use only # @!visibility private def update_data(new_data) @name = new_data[:name] || new_data['name'] || @name @hoist = new_data['hoist'] unless new_data['hoist'].nil? @hoist = new_data[:hoist] unless new_data[:hoist].nil? @colour = new_data[:colour] || (new_data['color'] ? ColourRGB.new(new_data['color']) : @colour) end # Sets the role name to something new # @param name [String] The name that should be set def name=(name) update_role_data(name: name) end # Changes whether or not this role is displayed at the top of the user list # @param hoist [true, false] The value it should be changed to def hoist=(hoist) update_role_data(hoist: hoist) end # Changes whether or not this role can be mentioned # @param mentionable [true, false] The value it should be changed to def mentionable=(mentionable) update_role_data(mentionable: mentionable) end # Sets the role colour to something new # @param colour [ColourRGB] The new colour def colour=(colour) update_role_data(colour: colour) end alias_method :color=, :colour= # Changes this role's permissions to a fixed bitfield. This allows setting multiple permissions at once with just # one API call. # # Information on how this bitfield is structured can be found at # https://discordapp.com/developers/docs/topics/permissions. # @example Remove all permissions from a role # role.packed = 0 # @param packed [Integer] A bitfield with the desired permissions value. # @param update_perms [true, false] Whether the internal data should also be updated. This should always be true # when calling externally. def packed=(packed, update_perms = true) update_role_data(permissions: packed) @permissions.bits = packed if update_perms end # Deletes this role. This cannot be undone without recreating the role! def delete API::Server.delete_role(@bot.token, @server.id, @id) @server.delete_role(@id) end # The inspect method is overwritten to give more useful output def inspect "<Role name=#{@name} permissions=#{@permissions.inspect} hoist=#{@hoist} colour=#{@colour.inspect} server=#{@server.inspect}>" end private def update_role_data(new_data) API::Server.update_role(@bot.token, @server.id, @id, new_data[:name] || @name, (new_data[:colour] || @colour).combined, new_data[:hoist].nil? ? @hoist : new_data[:hoist], new_data[:mentionable].nil? ? @mentionable : new_data[:mentionable], new_data[:permissions] || @permissions.bits) update_data(new_data) end end # A channel referenced by an invite. It has less data than regular channels, so it's a separate class class InviteChannel include IDObject # @return [String] this channel's name. attr_reader :name # @return [Integer] this channel's type (0: text, 1: private, 2: voice, 3: group). attr_reader :type # @!visibility private def initialize(data, bot) @bot = bot @id = data['id'].to_i @name = data['name'] @type = data['type'] end end # A server referenced to by an invite class InviteServer include IDObject # @return [String] this server's name. attr_reader :name # @return [String, nil] the hash of the server's invite splash screen (for partnered servers) or nil if none is # present attr_reader :splash_hash # @!visibility private def initialize(data, bot) @bot = bot @id = data['id'].to_i @name = data['name'] @splash_hash = data['splash_hash'] end end # A Discord invite to a channel class Invite # @return [InviteChannel] the channel this invite references. attr_reader :channel # @return [InviteServer] the server this invite references. attr_reader :server # @return [Integer] the amount of uses left on this invite. attr_reader :uses alias_method :max_uses, :uses # @return [User, nil] the user that made this invite. May also be nil if the user can't be determined. attr_reader :inviter alias_method :user, :inviter # @return [true, false] whether or not this invite is temporary. attr_reader :temporary alias_method :temporary?, :temporary # @return [true, false] whether this invite is still valid. attr_reader :revoked alias_method :revoked?, :revoked # @return [String] this invite's code attr_reader :code # @!visibility private def initialize(data, bot) @bot = bot @channel = InviteChannel.new(data['channel'], bot) @server = InviteServer.new(data['guild'], bot) @uses = data['uses'] @inviter = data['inviter'] ? (@bot.user(data['inviter']['id'].to_i) || User.new(data['inviter'], bot)) : nil @temporary = data['temporary'] @revoked = data['revoked'] @code = data['code'] end # Code based comparison def ==(other) other.respond_to?(:code) ? (@code == other.code) : (@code == other) end # Deletes this invite def delete API::Invite.delete(@bot.token, @code) end alias_method :revoke, :delete # The inspect method is overwritten to give more useful output def inspect "<Invite code=#{@code} channel=#{@channel} uses=#{@uses} temporary=#{@temporary} revoked=#{@revoked}>" end # Creates an invite URL. def url "https://discord.gg/#{@code}" end end # A Discord channel, including data like the topic class Channel include IDObject # @return [String] this channel's name. attr_reader :name # @return [Server, nil] the server this channel is on. If this channel is a PM channel, it will be nil. attr_reader :server # @return [Integer] the type of this channel (0: text, 1: private, 2: voice, 3: group) attr_reader :type # @return [Integer, nil] the id of the owner of the group channel or nil if this is not a group channel. attr_reader :owner_id # @return [Array<Recipient>, nil] the array of recipients of the private messages, or nil if this is not a Private channel attr_reader :recipients # @return [String] the channel's topic attr_reader :topic # @return [Integer] the bitrate (in bps) of the channel attr_reader :bitrate # @return [Integer] the amount of users that can be in the channel. `0` means it is unlimited. attr_reader :user_limit alias_method :limit, :user_limit # @return [Integer] the channel's position on the channel list attr_reader :position # This channel's permission overwrites, represented as a hash of role/user ID to an OpenStruct which has the # `allow` and `deny` properties which are {Permissions} objects respectively. # @return [Hash<Integer => OpenStruct>] the channel's permission overwrites attr_reader :permission_overwrites # @return [true, false] whether or not this channel is a PM or group channel. def private? pm? || group? end # @return [String] a string that will mention the channel as a clickable link on Discord. def mention "<##{@id}>" end # @return [Recipient, nil] the recipient of the private messages, or nil if this is not a PM channel def recipient @recipients.first if pm? end # @!visibility private def initialize(data, bot, server = nil) @bot = bot # data is a sometimes a Hash and other times an array of Hashes, you only want the last one if it's an array data = data[-1] if data.is_a?(Array) @id = data['id'].to_i @type = data['type'] || 0 @topic = data['topic'] @bitrate = data['bitrate'] @user_limit = data['user_limit'] @position = data['position'] if private? @recipients = [] if data['recipients'] data['recipients'].each do |recipient| recipient_user = bot.ensure_user(recipient) @recipients << Recipient.new(recipient_user, self, bot) end end if pm? @name = @recipients.first.username else @name = data['name'] @owner_id = data['owner_id'] end else @name = data['name'] @server = if server server else bot.server(data['guild_id'].to_i) end end # Populate permission overwrites @permission_overwrites = {} return unless data['permission_overwrites'] data['permission_overwrites'].each do |element| role_id = element['id'].to_i deny = Permissions.new(element['deny']) allow = Permissions.new(element['allow']) @permission_overwrites[role_id] = OpenStruct.new @permission_overwrites[role_id].deny = deny @permission_overwrites[role_id].allow = allow end end # @return [true, false] whether or not this channel is a text channel def text? @type.zero? end # @return [true, false] whether or not this channel is a PM channel. def pm? @type == 1 end # @return [true, false] whether or not this channel is a voice channel. def voice? @type == 2 end # @return [true, false] whether or not this channel is a group channel. def group? @type == 3 end # Sends a message to this channel. # @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error. # @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech. # @return [Message] the message that was sent. def send_message(content, tts = false) @bot.send_message(@id, content, tts, @server && @server.id) end alias_method :send, :send_message # Sends a temporary message to this channel. # @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error. # @param timeout [Float] The amount of time in seconds after which the message sent will be deleted. # @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech. def send_temporary_message(content, timeout, tts = false) @bot.send_temporary_message(@id, content, timeout, tts, @server && @server.id) end # Sends multiple messages to a channel # @param content [Array<String>] The messages to send. def send_multiple(content) content.each { |e| send_message(e) } end # Splits a message into chunks whose length is at most the Discord character limit, then sends them individually. # Useful for sending long messages, but be wary of rate limits! def split_send(content) send_multiple(Discordrb.split_message(content)) end # Sends a file to this channel. If it is an image, it will be embedded. # @param file [File] The file to send. There's no clear size limit for this, you'll have to attempt it for yourself (most non-image files are fine, large images may fail to embed) # @param caption [string] The caption for the file. # @param tts [true, false] Whether or not this file's caption should be sent using Discord text-to-speech. def send_file(file, caption: nil, tts: false) @bot.send_file(@id, file, caption: caption, tts: tts) end # Permanently deletes this channel def delete API::Channel.delete(@bot.token, @id) end # Sets this channel's name. The name must be alphanumeric with dashes, unless this is a voice channel (then there are no limitations) # @param name [String] The new name. def name=(name) @name = name update_channel_data end # Sets this channel's topic. # @param topic [String] The new topic. def topic=(topic) raise 'Tried to set topic on voice channel' if voice? @topic = topic update_channel_data end # Sets this channel's bitrate. # @param bitrate [Integer] The new bitrate (in bps). Number has to be between 8000-96000 (128000 for VIP servers) def bitrate=(bitrate) raise 'Tried to set bitrate on text channel' if text? @bitrate = bitrate update_channel_data end # Sets this channel's user limit. # @param limit [Integer] The new user limit. `0` for unlimited, has to be a number between 0-99 def user_limit=(limit) raise 'Tried to set user_limit on text channel' if text? @user_limit = limit update_channel_data end alias_method :limit=, :user_limit= # Sets this channel's position in the list. # @param position [Integer] The new position. def position=(position) @position = position update_channel_data end # Defines a permission overwrite for this channel that sets the specified thing to the specified allow and deny # permission sets, or change an existing one. # @param thing [User, Role] What to define an overwrite for. # @param allow [#bits, Permissions, Integer] The permission sets that should receive an `allow` override (i. e. a # green checkmark on Discord) # @param deny [#bits, Permissions, Integer] The permission sets that should receive a `deny` override (i. e. a red # cross on Discord) # @example Define a permission overwrite for a user that can then mention everyone and use TTS, but not create any invites # allow = Discordrb::Permissions.new # allow.can_mention_everyone = true # allow.can_send_tts_messages = true # # deny = Discordrb::Permissions.new # deny.can_create_instant_invite = true # # channel.define_overwrite(user, allow, deny) def define_overwrite(thing, allow, deny) allow_bits = allow.respond_to?(:bits) ? allow.bits : allow deny_bits = deny.respond_to?(:bits) ? deny.bits : deny type = if thing.is_a?(User) || thing.is_a?(Member) || thing.is_a?(Recipient) || thing.is_a?(Profile) :member elsif thing.is_a? Role :role else raise ArgumentError, '`thing` in define_overwrite needs to be a kind of User (User, Member, Recipient, Profile) or a Role!' end API::Channel.update_permission(@bot.token, @id, thing.id, allow_bits, deny_bits, type) end # Updates the cached data from another channel. # @note For internal use only # @!visibility private def update_from(other) @topic = other.topic @name = other.name @permission_overwrites = other.permission_overwrites end # The list of users currently in this channel. For a voice channel, it will return all the members currently # in that channel. For a text channel, it will return all online members that have permission to read it. # @return [Array<Member>] the users in this channel def users if text? @server.online_members(include_idle: true).select { |u| u.can_read_messages? self } elsif voice? @server.voice_states.map { |id, voice_state| @server.member(id) if !voice_state.voice_channel.nil? && voice_state.voice_channel.id == @id }.compact end end # Retrieves some of this channel's message history. # @param amount [Integer] How many messages to retrieve. This must be less than or equal to 100, if it is higher # than 100 it will be treated as 100 on Discord's side. # @param before_id [Integer] The ID of the most recent message the retrieval should start at, or nil if it should # start at the current message. # @param after_id [Integer] The ID of the oldest message the retrieval should start at, or nil if it should start # as soon as possible with the specified amount. # @example Count the number of messages in the last 50 messages that contain the letter 'e'. # message_count = channel.history(50).count {|message| message.content.include? "e"} # @return [Array<Message>] the retrieved messages. def history(amount, before_id = nil, after_id = nil) logs = API::Channel.messages(@bot.token, @id, amount, before_id, after_id) JSON.parse(logs).map { |message| Message.new(message, @bot) } end # Retrieves message history, but only message IDs for use with prune # @note For internal use only # @!visibility private def history_ids(amount, before_id = nil, after_id = nil) logs = API::Channel.messages(@bot.token, @id, amount, before_id, after_id) JSON.parse(logs).map { |message| message['id'] } end # Returns a single message from this channel's history by ID. # @param message_id [Integer] The ID of the message to retrieve. # @return [Message] the retrieved message. def load_message(message_id) response = API::Channel.message(@bot.token, @id, message_id) return Message.new(JSON.parse(response), @bot) rescue RestClient::ResourceNotFound return nil end alias_method :message, :load_message # Requests all pinned messages of a channel. # @return [Array<Message>] the received messages. def pins msgs = API::Channel.pinned_messages(@bot.token, @id) JSON.parse(msgs).map { |msg| Message.new(msg, @bot) } end # Delete the last N messages on this channel. # @param amount [Integer] How many messages to delete. Must be a value between 2 and 100 (Discord limitation) # @raise [ArgumentError] if the amount of messages is not a value between 2 and 100 def prune(amount) raise ArgumentError, 'Can only prune between 2 and 100 messages!' unless amount.between?(2, 100) messages = history_ids(amount) API::Channel.bulk_delete_messages(@bot.token, @id, messages) end # Deletes a collection of messages # @param messages [Array<Message, Integer>] the messages (or message IDs) to delete. Total must be an amount between 2 and 100 (Discord limitation) # @raise [ArgumentError] if the amount of messages is not a value between 2 and 100 def delete_messages(messages) raise ArgumentError, 'Can only delete between 2 and 100 messages!' unless messages.count.between?(2, 100) messages.map!(&:resolve_id) API::Channel.bulk_delete_messages(@bot.token, @id, messages) end # Updates the cached permission overwrites # @note For internal use only # @!visibility private def update_overwrites(overwrites) @permission_overwrites = overwrites end # Add an {Await} for a message in this channel. This is identical in functionality to adding a # {Discordrb::Events::MessageEvent} await with the `in` attribute as this channel. # @see Bot#add_await def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { in: @id }.merge(attributes), &block) end # Creates a new invite to this channel. # @param max_age [Integer] How many seconds this invite should last. # @param max_uses [Integer] How many times this invite should be able to be used. # @param temporary [true, false] Whether membership should be temporary (kicked after going offline). # @return [Invite] the created invite. def make_invite(max_age = 0, max_uses = 0, temporary = false) response = API::Channel.create_invite(@bot.token, @id, max_age, max_uses, temporary) Invite.new(JSON.parse(response), @bot) end alias_method :invite, :make_invite # Starts typing, which displays the typing indicator on the client for five seconds. # If you want to keep typing you'll have to resend this every five seconds. (An abstraction # for this will eventually be coming) def start_typing API::Channel.start_typing(@bot.token, @id) end # Creates a Group channel # @param user_ids [Array<Integer>] Array of user IDs to add to the new group channel (Excluding # the recipient of the PM channel). # @return [Channel] the created channel. def create_group(user_ids) raise 'Attempted to create group channel on a non-pm channel!' unless pm? response = API::Channel.create_group(@bot.token, @id, user_ids.shift) channel = Channel.new(JSON.parse(response), @bot) channel.add_group_users(user_ids) end # Adds a user to a Group channel # @param user_ids [Array<#resolve_id>, #resolve_id] User ID or array of user IDs to add to the group channel. # @return [Channel] the group channel. def add_group_users(user_ids) raise 'Attempted to add a user to a non-group channel!' unless group? user_ids = [user_ids] unless user_ids.is_a? Array user_ids.each do |user_id| API::Channel.add_group_user(@bot.token, @id, user_id.resolve_id) end self end alias_method :add_group_user, :add_group_users # Removes a user from a group channel. # @param user_ids [Array<#resolve_id>, #resolve_id] User ID or array of user IDs to remove from the group channel. # @return [Channel] the group channel. def remove_group_users(user_ids) raise 'Attempted to remove a user from a non-group channel!' unless group? user_ids = [user_ids] unless user_ids.is_a? Array user_ids.each do |user_id| API::Channel.remove_group_user(@bot.token, @id, user_id.resolve_id) end self end alias_method :remove_group_user, :remove_group_users # Leaves the group def leave_group raise 'Attempted to leave a non-group channel!' unless group? API::Channel.leave_group(@bot.token, @id) end alias_method :leave, :leave_group # The inspect method is overwritten to give more useful output def inspect "<Channel name=#{@name} id=#{@id} topic=\"#{@topic}\" type=#{@type} position=#{@position} server=#{@server}>" end # Adds a recipient to a group channel. # @param recipient [Recipient] the recipient to add to the group # @raise [ArgumentError] if tried to add a non-recipient # @note For internal use only # @!visibility private def add_recipient(recipient) raise 'Tried to add recipient to a non-group channel' unless group? raise ArgumentError, 'Tried to add a non-recipient to a group' unless recipient.is_a?(Recipient) @recipients << recipient end # Removes a recipient from a group channel. # @param recipient [Recipient] the recipient to remove from the group # @raise [ArgumentError] if tried to remove a non-recipient # @note For internal use only # @!visibility private def remove_recipient(recipient) raise 'Tried to add recipient to a non-group channel' unless group? raise ArgumentError, 'Tried to remove a non-recipient from a group' unless recipient.is_a?(Recipient) @recipients.delete(recipient) end private def update_channel_data API::Channel.update(@bot.token, @id, @name, @topic, @position, @bitrate, @user_limit) end end # An Embed object that is contained in a message # A freshly generated embed object will not appear in a message object # unless grabbed from its ID in a channel. class Embed # @return [Message] the message this embed object is contained in. attr_reader :message # @return [String] the URL this embed object is based on. attr_reader :url # @return [String, nil] the title of the embed object. `nil` if there is not a title attr_reader :title # @return [String, nil] the description of the embed object. `nil` if there is not a description attr_reader :description # @return [Symbol] the type of the embed object. Possible types are: # # * `:link` # * `:video` # * `:image` attr_reader :type # @return [EmbedProvider, nil] the provider of the embed object. `nil` is there is not a provider attr_reader :provider # @return [EmbedThumbnail, nil] the thumbnail of the embed object. `nil` is there is not a thumbnail attr_reader :thumbnail # @return [EmbedAuthor, nil] the author of the embed object. `nil` is there is not an author attr_reader :author # @!visibility private def initialize(data, message) @message = message @url = data['url'] @title = data['title'] @type = data['type'].to_sym @description = data['description'] @provider = data['provider'].nil? ? nil : EmbedProvider.new(data['provider'], self) @thumbnail = data['thumbnail'].nil? ? nil : EmbedThumbnail.new(data['thumbnail'], self) @author = data['author'].nil? ? nil : EmbedAuthor.new(data['author'], self) end end # An Embed thumbnail for the embed object class EmbedThumbnail # @return [Embed] the embed object this is based on. attr_reader :embed # @return [String] the CDN URL this thumbnail can be downloaded at. attr_reader :url # @return [String] the thumbnail's proxy URL - I'm not sure what exactly this does, but I think it has something to # do with CDNs attr_reader :proxy_url # @return [Integer] the width of this thumbnail file, in pixels. attr_reader :width # @return [Integer] the height of this thumbnail file, in pixels. attr_reader :height # @!visibility private def initialize(data, embed) @embed = embed @url = data['url'] @proxy_url = data['proxy_url'] @width = data['width'] @height = data['height'] end end # An Embed provider for the embed object class EmbedProvider # @return [Embed] the embed object this is based on. attr_reader :embed # @return [String] the provider's name. attr_reader :name # @return [String, nil] the URL of the provider. `nil` is there is no URL attr_reader :url # @!visibility private def initialize(data, embed) @embed = embed @name = data['name'] @url = data['url'] end end # An Embed author for the embed object class EmbedAuthor # @return [Embed] the embed object this is based on. attr_reader :embed # @return [String] the author's name. attr_reader :name # @return [String, nil] the URL of the author's website. `nil` is there is no URL attr_reader :url # @!visibility private def initialize(data, embed) @embed = embed @name = data['name'] @url = data['url'] end end # An attachment to a message class Attachment include IDObject # @return [Message] the message this attachment belongs to. attr_reader :message # @return [String] the CDN URL this attachment can be downloaded at. attr_reader :url # @return [String] the attachment's proxy URL - I'm not sure what exactly this does, but I think it has something to # do with CDNs attr_reader :proxy_url # @return [String] the attachment's filename. attr_reader :filename # @return [Integer] the attachment's file size in bytes. attr_reader :size # @return [Integer, nil] the width of an image file, in pixels, or nil if the file is not an image. attr_reader :width # @return [Integer, nil] the height of an image file, in pixels, or nil if the file is not an image. attr_reader :height # @!visibility private def initialize(data, message, bot) @bot = bot @message = message @url = data['url'] @proxy_url = data['proxy_url'] @filename = data['filename'] @size = data['size'] @width = data['width'] @height = data['height'] end # @return [true, false] whether this file is an image file. def image? !(@width.nil? || @height.nil?) end end # A message on Discord that was sent to a text channel class Message include IDObject # @return [String] the content of this message. attr_reader :content alias_method :text, :content alias_method :to_s, :content # @return [Member] the user that sent this message. attr_reader :author alias_method :user, :author alias_method :writer, :author # @return [Channel] the channel in which this message was sent. attr_reader :channel # @return [Time] the timestamp at which this message was sent. attr_reader :timestamp # @return [Time] the timestamp at which this message was edited. `nil` if the message was never edited. attr_reader :edited_timestamp alias_method :edit_timestamp, :edited_timestamp # @return [Array<User>] the users that were mentioned in this message. attr_reader :mentions # @return [Array<Role>] the roles that were mentioned in this message. attr_reader :role_mentions # @return [Array<Attachment>] the files attached to this message. attr_reader :attachments # @return [Array<Embed>] the embed objects contained in this message. attr_reader :embeds # @return [true, false] whether the message used Text-To-Speech (TTS) or not. attr_reader :tts alias_method :tts?, :tts # @return [String] used for validating a message was sent attr_reader :nonce # @return [true, false] whether the message was edited or not. attr_reader :edited alias_method :edited?, :edited # @return [true, false] whether the message mentioned everyone or not. attr_reader :mention_everyone alias_method :mention_everyone?, :mention_everyone alias_method :mentions_everyone?, :mention_everyone # @return [true, false] whether the message is pinned or not. attr_reader :pinned alias_method :pinned?, :pinned # @return [Integer, nil] the webhook ID that sent this message, or nil if it wasn't sent through a webhook. attr_reader :webhook_id # The discriminator that webhook user accounts have. ZERO_DISCRIM = '0000'.freeze # @!visibility private def initialize(data, bot) @bot = bot @content = data['content'] @channel = bot.channel(data['channel_id'].to_i) @pinned = data['pinned'] @tts = data['tts'] @nonce = data['nonce'] @mention_everyone = data['mention_everyone'] @author = if data['author'] if data['author']['discriminator'] == ZERO_DISCRIM # This is a webhook user! It would be pointless to try to resolve a member here, so we just create # a User and return that instead. Discordrb::LOGGER.debug("Webhook user: #{data['author']['id']}") User.new(data['author'], @bot) elsif @channel.private? # Turn the message user into a recipient - we can't use the channel recipient # directly because the bot may also send messages to the channel Recipient.new(bot.user(data['author']['id'].to_i), @channel, bot) else member = @channel.server.member(data['author']['id'].to_i) Discordrb::LOGGER.warn("Member with ID #{data['author']['id']} not cached even though it should be.") unless member member end end @webhook_id = data['webhook_id'].to_i if data['webhook_id'] @timestamp = Time.parse(data['timestamp']) if data['timestamp'] @edited_timestamp = data['edited_timestamp'].nil? ? nil : Time.parse(data['edited_timestamp']) @edited = !@edited_timestamp.nil? @id = data['id'].to_i @emoji = [] @mentions = [] data['mentions'].each do |element| @mentions << bot.ensure_user(element) end if data['mentions'] @role_mentions = [] # Role mentions can only happen on public servers so make sure we only parse them there if @channel.text? data['mention_roles'].each do |element| @role_mentions << @channel.server.role(element.to_i) end if data['mention_roles'] end @attachments = [] @attachments = data['attachments'].map { |e| Attachment.new(e, self, @bot) } if data['attachments'] @embeds = [] @embeds = data['embeds'].map { |e| Embed.new(e, self) } if data['embeds'] end # Replies to this message with the specified content. # @see Channel#send_message def reply(content) @channel.send_message(content) end # Edits this message to have the specified content instead. # You can only edit your own messages. # @param new_content [String] the new content the message should have. # @return [Message] the resulting message. def edit(new_content) response = API::Channel.edit_message(@bot.token, @channel.id, @id, new_content) Message.new(JSON.parse(response), @bot) end # Deletes this message. def delete API::Channel.delete_message(@bot.token, @channel.id, @id) nil end # Pins this message def pin API::Channel.pin_message(@bot.token, @channel.id, @id) @pinned = true nil end # Unpins this message def unpin API::Channel.unpin_message(@bot.token, @channel.id, @id) @pinned = false nil end # Add an {Await} for a message with the same user and channel. # @see Bot#add_await def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { from: @author.id, in: @channel.id }.merge(attributes), &block) end # @return [true, false] whether this message was sent by the current {Bot}. def from_bot? @author && @author.current_bot? end # @return [true, false] whether this message has been sent over a webhook. def webhook? !@webhook_id.nil? end # @!visibility private # @return [Array<String>] the emoji mentions found in the message def scan_for_emoji emoji = @content.split emoji = emoji.grep(/<:(?<name>\w+):(?<id>\d+)>?/) emoji end # @return [Array<Emoji>] the emotes that were used/mentioned in this message (Only returns Emoji the bot has access to, else nil). def emoji return if @content.nil? emoji = scan_for_emoji emoji.each do |element| @emoji << @bot.parse_mention(element) end @emoji end # Check if any emoji got used in this message # @return [true, false] whether or not any emoji got used def emoji? emoji = scan_for_emoji return true unless emoji.empty? end # The inspect method is overwritten to give more useful output def inspect "<Message content=\"#{@content}\" id=#{@id} timestamp=#{@timestamp} author=#{@author} channel=#{@channel}>" end end # Server emoji class Emoji include IDObject # @return [String] the emoji name attr_reader :name # @return [Server] the server of this emoji attr_reader :server # @return [Array<Role>] roles this emoji is active for attr_reader :roles def initialize(data, bot, server) @bot = bot @roles = nil @name = data['name'] @server = server @id = data['id'].to_i process_roles(data['roles']) if server end # @return [String] the layout to mention it (or have it used) in a message def mention "<:#{@name}:#{@id}>" end alias_method :use, :mention alias_method :to_s, :mention # @return [String] the icon URL of the emoji def icon_url API.emoji_icon_url(@id) end # The inspect method is overwritten to give more useful output def inspect "<Emoji name=#{@name} id=#{@id}>" end # @!visibility private def process_roles(roles) @roles = [] return unless roles roles.each do |role_id| role = server.role(role_id) @roles << role end end end # Emoji that is not tailored to a server class GlobalEmoji include IDObject # @return [String] the emoji name attr_reader :name # @return [Hash<Integer => Array<Role>>] roles this emoji is active for in every server attr_reader :role_associations def initialize(data, bot) @bot = bot @roles = nil @name = data.name @id = data.id @role_associations = Hash.new([]) @role_associations[data.server.id] = data.roles end # @return [String] the layout to mention it (or have it used) in a message def mention "<:#{@name}:#{@id}>" end alias_method :use, :mention alias_method :to_s, :mention # @return [String] the icon URL of the emoji def icon_url API.emoji_icon_url(@id) end # The inspect method is overwritten to give more useful output def inspect "<GlobalEmoji name=#{@name} id=#{@id}>" end # @!visibility private def process_roles(roles) new_roles = [] return unless roles roles.each do role = server.role(role_id) new_roles << role end new_roles end end # Basic attributes a server should have module ServerAttributes # @return [String] this server's name. attr_reader :name # @return [String] the hexadecimal ID used to identify this server's icon. attr_reader :icon_id # Utility function to get the URL for the icon image # @return [String] the URL to the icon image def icon_url return nil unless @icon_id API.icon_url(@id, @icon_id) end end # Integration Account class IntegrationAccount # @return [String] this account's name. attr_reader :name # @return [Integer] this account's ID. attr_reader :id def initialize(data) @name = data['name'] @id = data['id'].to_i end end # Server integration class Integration include IDObject # @return [String] the integration name attr_reader :name # @return [Server] the server the integration is linked to attr_reader :server # @return [User] the user the integration is linked to attr_reader :user # @return [Role, nil] the role that this integration uses for "subscribers" attr_reader :role # @return [true, false] whether emoticons are enabled attr_reader :emoticon alias_method :emoticon?, :emoticon # @return [String] the integration type (Youtube, Twitch, etc.) attr_reader :type # @return [true, false] whether the integration is enabled attr_reader :enabled # @return [true, false] whether the integration is syncing attr_reader :syncing # @return [IntegrationAccount] the integration account information attr_reader :account # @return [Time] the time the integration was synced at attr_reader :synced_at # @return [Symbol] the behaviour of expiring subscribers (:remove = Remove User from role; :kick = Kick User from server) attr_reader :expire_behaviour alias_method :expire_behavior, :expire_behaviour # @return [Integer] the grace period before subscribers expire (in days) attr_reader :expire_grace_period def initialize(data, bot, server) @bot = bot @name = data['name'] @server = server @id = data['id'].to_i @enabled = data['enabled'] @syncing = data['syncing'] @type = data['type'] @account = IntegrationAccount.new(data['account']) @synced_at = Time.parse(data['synced_at']) @expire_behaviour = [:remove, :kick][data['expire_behavior']] @expire_grace_period = data['expire_grace_period'] @user = @bot.ensure_user(data['user']) @role = server.role(data['role_id']) || nil @emoticon = data['enable_emoticons'] end # The inspect method is overwritten to give more useful output def inspect "<Integration name=#{@name} id=#{@id} type=#{@type} enabled=#{@enabled}>" end end # A server on Discord class Server include IDObject include ServerAttributes # @return [String] the region the server is on (e. g. `amsterdam`). attr_reader :region # @return [Member] The server owner. attr_reader :owner # @return [Array<Channel>] an array of all the channels (text and voice) on this server. attr_reader :channels # @return [Array<Role>] an array of all the roles created on this server. attr_reader :roles # @return [Array<Emoji>] an array of all the emoji available on this server. attr_reader :emoji alias_method :emojis, :emoji # @return [true, false] whether or not this server is large (members > 100). If it is, # it means the members list may be inaccurate for a couple seconds after starting up the bot. attr_reader :large alias_method :large?, :large # @return [Array<Symbol>] the features of the server (eg. "INVITE_SPLASH") attr_reader :features # @return [Integer] the absolute number of members on this server, offline or not. attr_reader :member_count # @return [Symbol] the verification level of the server (:none = none, :low = 'Must have a verified email on their Discord account', :medium = 'Has to be registered with Discord for at least 5 minutes', :high = 'Has to be a member of this server for at least 10 minutes'). attr_reader :verification_level # @return [Integer] the amount of time after which a voice user gets moved into the AFK channel, in seconds. attr_reader :afk_timeout # @return [Channel, nil] the AFK voice channel of this server, or nil if none is set attr_reader :afk_channel # @return [Hash<Integer => VoiceState>] the hash (user ID => voice state) of voice states of members on this server attr_reader :voice_states # @!visibility private def initialize(data, bot, exists = true) @bot = bot @owner_id = data['owner_id'].to_i @id = data['id'].to_i update_data(data) @large = data['large'] @member_count = data['member_count'] @verification_level = [:none, :low, :medium, :high][data['verification_level']] @splash_id = nil @embed = nil @features = data['features'].map { |element| element.downcase.to_sym } @members = {} @voice_states = {} @emoji = {} process_roles(data['roles']) process_emoji(data['emojis']) process_members(data['members']) process_presences(data['presences']) process_channels(data['channels']) process_voice_states(data['voice_states']) # Whether this server's members have been chunked (resolved using op 8 and GUILD_MEMBERS_CHUNK) yet @chunked = false @processed_chunk_members = 0 # Only get the owner of the server actually exists (i. e. not for ServerDeleteEvent) @owner = member(@owner_id) if exists end # @return [Channel] The default channel on this server (usually called #general) def default_channel @bot.channel(@id) end alias_method :general_channel, :default_channel # Gets a role on this server based on its ID. # @param id [Integer] The role ID to look for. def role(id) @roles.find { |e| e.id == id } end # Gets a member on this server based on user ID # @param id [Integer] The user ID to look for # @param request [true, false] Whether the member should be requested from Discord if it's not cached def member(id, request = true) id = id.resolve_id return @members[id] if member_cached?(id) return nil unless request member = @bot.member(self, id) @members[id] = member rescue nil end # @return [Array<Member>] an array of all the members on this server. def members return @members.values if @chunked @bot.debug("Members for server #{@id} not chunked yet - initiating") @bot.request_chunks(@id) sleep 0.05 until @chunked @members.values end alias_method :users, :members # @return [Array<Integration>] an array of all the integrations connected to this server. def integrations integration = JSON.parse(API.server_integrations(@bot.token, @id)) integration.map { |element| Integration.new(element, @bot, self) } end # Cache @embed # @note For internal use only # @!visibility private def cache_embed @embed = JSON.parse(API.server(@bot.token, @id))['embed_enabled'] if @embed.nil? end # @return [true, false] whether or not the server has widget enabled def embed? cache_embed if @embed.nil? @embed end # @param include_idle [true, false] Whether to count idle members as online. # @param include_bots [true, false] Whether to include bot accounts in the count. # @return [Array<Member>] an array of online members on this server. def online_members(include_idle: false, include_bots: true) @members.values.select do |e| ((include_idle ? e.idle? : false) || e.online?) && (include_bots ? true : !e.bot_account?) end end alias_method :online_users, :online_members # @return [Array<Channel>] an array of text channels on this server def text_channels @channels.select(&:text?) end # @return [Array<Channel>] an array of voice channels on this server def voice_channels @channels.select(&:voice?) end # @return [String, nil] the widget URL to the server that displays the amount of online members in a # stylish way. `nil` if the widget is not enabled. def widget_url cache_embed if @embed.nil? return nil unless @embed API.widget_url(@id) end # @param style [Symbol] The style the picture should have. Possible styles are: # * `:banner1` creates a rectangular image with the server name, member count and icon, a "Powered by Discord" message on the bottom and an arrow on the right. # * `:banner2` creates a less tall rectangular image that has the same information as `banner1`, but the Discord logo on the right - together with the arrow and separated by a diagonal separator. # * `:banner3` creates an image similar in size to `banner1`, but it has the arrow in the bottom part, next to the Discord logo and with a "Chat now" text. # * `:banner4` creates a tall, almost square, image that prominently features the Discord logo at the top and has a "Join my server" in a pill-style button on the bottom. The information about the server is in the same format as the other three `banner` styles. # * `:shield` creates a very small, long rectangle, of the style you'd find at the top of GitHub `README.md` files. It features a small version of the Discord logo at the left and the member count at the right. # @return [String, nil] the widget banner URL to the server that displays the amount of online members, # server icon and server name in a stylish way. `nil` if the widget is not enabled. def widget_banner_url(style) return nil unless @embed cache_embed if @embed.nil? API.widget_url(@id, style) end # @return [String] the hexadecimal ID used to identify this server's splash image for their VIP invite page. def splash_id @splash_id = JSON.parse(API.server(@bot.token, @id))['splash'] if @splash_id.nil? @splash_id end # @return [String, nil] the splash image URL for the server's VIP invite page. # `nil` if there is no splash image. def splash_url splash_id if @splash_id.nil? return nil unless @splash_id API.splash_url(@id, @splash_id) end # Adds a role to the role cache # @note For internal use only # @!visibility private def add_role(role) @roles << role end # Removes a role from the role cache # @note For internal use only # @!visibility private def delete_role(role_id) @roles.reject! { |r| r.id == role_id } @members.each do |_, member| new_roles = member.roles.reject { |r| r.id == role_id } member.update_roles(new_roles) end @channels.each do |channel| overwrites = channel.permission_overwrites.reject { |id, _| id == role_id } channel.update_overwrites(overwrites) end end # Adds a member to the member cache. # @note For internal use only # @!visibility private def add_member(member) @members[member.id] = member @member_count += 1 end # Removes a member from the member cache. # @note For internal use only # @!visibility private def delete_member(user_id) @members.delete(user_id) @member_count -= 1 end # Checks whether a member is cached # @note For internal use only # @!visibility private def member_cached?(user_id) @members.include?(user_id) end # Adds a member to the cache # @note For internal use only # @!visibility private def cache_member(member) @members[member.id] = member end # Updates a member's voice state # @note For internal use only # @!visibility private def update_voice_state(data) user_id = data['user_id'].to_i if data['channel_id'] unless @voice_states[user_id] # Create a new voice state for the user @voice_states[user_id] = VoiceState.new(user_id) end # Update the existing voice state (or the one we just created) channel = @channels_by_id[data['channel_id'].to_i] @voice_states[user_id].update( channel, data['mute'], data['deaf'], data['self_mute'], data['self_deaf'] ) else # The user is not in a voice channel anymore, so delete its voice state @voice_states.delete(user_id) end end # Creates a channel on this server with the given name. # @param name [String] Name of the channel to create # @param type [Integer] Type of channel to create (0: text, 2: voice) # @return [Channel] the created channel. # @raise [ArgumentError] if type is not 0 or 2 def create_channel(name, type = 0) raise ArgumentError, 'Channel type must be either 0 (text) or 2 (voice)!' unless [0, 2].include?(type) response = API::Server.create_channel(@bot.token, @id, name, type) Channel.new(JSON.parse(response), @bot) end # Creates a role on this server which can then be modified. It will be initialized (on Discord's side) # with the regular role defaults the client uses, i. e. name is "new role", permissions are the default, # colour is the default etc. # @return [Role] the created role. def create_role response = API::Server.create_role(@bot.token, @id) role = Role.new(JSON.parse(response), @bot, self) @roles << role role end # @return [Array<User>] a list of banned users on this server. def bans users = JSON.parse(API::Server.bans(@bot.token, @id)) users.map { |e| User.new(e['user'], @bot) } end # Bans a user from this server. # @param user [User, #resolve_id] The user to ban. # @param message_days [Integer] How many days worth of messages sent by the user should be deleted. def ban(user, message_days = 0) API::Server.ban_user(@bot.token, @id, user.resolve_id, message_days) end # Unbans a previously banned user from this server. # @param user [User, #resolve_id] The user to unban. def unban(user) API::Server.unban_user(@bot.token, @id, user.resolve_id) end # Kicks a user from this server. # @param user [User, #resolve_id] The user to kick. def kick(user) API::Server.remove_member(@bot.token, @id, user.resolve_id) end # Forcibly moves a user into a different voice channel. Only works if the bot has the permission needed. # @param user [User] The user to move. # @param channel [Channel] The voice channel to move into. def move(user, channel) API::Server.update_member(@bot.token, @id, user.id, channel_id: channel.id) end # Deletes this server. Be aware that this is permanent and impossible to undo, so be careful! def delete API::Server.delete(@bot.token, @id) end # Leave the server def leave API::User.leave_server(@bot.token, @id) end # Transfers server ownership to another user. # @param user [User] The user who should become the new owner. def owner=(user) API::Server.transfer_ownership(@bot.token, @id, user.id) end # Sets the server's name. # @param name [String] The new server name. def name=(name) update_server_data(name: name) end # Moves the server to another region. This will cause a voice interruption of at most a second. # @param region [String] The new region the server should be in. def region=(region) update_server_data(region: region.to_s) end # Sets the server's icon. # @param icon [String, #read] The new icon, in base64-encoded JPG format. def icon=(icon) if icon.respond_to? :read icon_string = 'data:image/jpg;base64,' icon_string += Base64.strict_encode64(icon.read) update_server_data(icon: icon_string) else update_server_data(icon: icon) end end # Sets the server's AFK channel. # @param afk_channel [Channel, nil] The new AFK channel, or `nil` if there should be none set. def afk_channel=(afk_channel) update_server_data(afk_channel_id: afk_channel.resolve_id) end # Sets the amount of time after which a user gets moved into the AFK channel. # @param afk_timeout [Integer] The AFK timeout, in seconds. def afk_timeout=(afk_timeout) update_server_data(afk_timeout: afk_timeout) end # @return [true, false] whether this server has any emoji or not. def any_emoji? @emoji.any? end alias_method :has_emoji?, :any_emoji? alias_method :emoji?, :any_emoji? # Processes a GUILD_MEMBERS_CHUNK packet, specifically the members field # @note For internal use only # @!visibility private def process_chunk(members) process_members(members) @processed_chunk_members += members.length LOGGER.debug("Processed one chunk on server #{@id} - length #{members.length}") # Don't bother with the rest of the method if it's not truly the last packet return unless @processed_chunk_members == @member_count LOGGER.debug("Finished chunking server #{@id}") # Reset everything to normal @chunked = true @processed_chunk_members = 0 end # Updates the cached data with new data # @note For internal use only # @!visibility private def update_data(new_data) @name = new_data[:name] || new_data['name'] || @name @region = new_data[:region] || new_data['region'] || @region @icon_id = new_data[:icon] || new_data['icon'] || @icon_id @afk_timeout = new_data[:afk_timeout] || new_data['afk_timeout'].to_i || @afk_timeout @afk_channel_id = new_data[:afk_channel_id] || new_data['afk_channel_id'].to_i || @afk_channel.id begin @afk_channel = @bot.channel(@afk_channel_id, self) if @afk_channel_id.nonzero? && (!@afk_channel || @afk_channel_id != @afk_channel.id) rescue Discordrb::Errors::NoPermission LOGGER.debug("AFK channel #{@afk_channel_id} on server #{@id} is unreachable, setting to nil even though one exists") @afk_channel = nil end end # The inspect method is overwritten to give more useful output def inspect "<Server name=#{@name} id=#{@id} large=#{@large} region=#{@region} owner=#{@owner} afk_channel_id=#{@afk_channel_id} afk_timeout=#{@afk_timeout}>" end private def update_server_data(new_data) API::Server.update(@bot.token, @id, new_data[:name] || @name, new_data[:region] || @region, new_data[:icon_id] || @icon_id, new_data[:afk_channel_id] || @afk_channel_id, new_data[:afk_timeout] || @afk_timeout) update_data(new_data) end def process_roles(roles) # Create roles @roles = [] @roles_by_id = {} return unless roles roles.each do |element| role = Role.new(element, @bot, self) @roles << role @roles_by_id[role.id] = role end end def process_emoji(emoji) return if emoji.empty? emoji.each do |element| new_emoji = Emoji.new(element, @bot, self) @emoji[new_emoji.id] = new_emoji end end def process_members(members) return unless members members.each do |element| member = Member.new(element, self, @bot) @members[member.id] = member end end def process_presences(presences) # Update user statuses with presence info return unless presences presences.each do |element| next unless element['user'] user_id = element['user']['id'].to_i user = @members[user_id] if user user.status = element['status'].to_sym user.game = element['game'] ? element['game']['name'] : nil else LOGGER.warn "Rogue presence update! #{element['user']['id']} on #{@id}" end end end def process_channels(channels) @channels = [] @channels_by_id = {} return unless channels channels.each do |element| channel = @bot.ensure_channel(element, self) @channels << channel @channels_by_id[channel.id] = channel end end def process_voice_states(voice_states) return unless voice_states voice_states.each do |element| update_voice_state(element) end end end # A colour (red, green and blue values). Used for role colours. If you prefer the American spelling, the alias # {ColorRGB} is also available. class ColourRGB # @return [Integer] the red part of this colour (0-255). attr_reader :red # @return [Integer] the green part of this colour (0-255). attr_reader :green # @return [Integer] the blue part of this colour (0-255). attr_reader :blue # @return [Integer] the colour's RGB values combined into one integer. attr_reader :combined # Make a new colour from the combined value. # @param combined [Integer] The colour's RGB values combined into one integer def initialize(combined) @combined = combined @red = (combined >> 16) & 0xFF @green = (combined >> 8) & 0xFF @blue = combined & 0xFF end end # Alias for the class {ColourRGB} ColorRGB = ColourRGB end add basic reaction support # frozen_string_literal: true # These classes hold relevant Discord data, such as messages or channels. require 'ostruct' require 'discordrb/permissions' require 'discordrb/errors' require 'discordrb/api' require 'discordrb/api/channel' require 'discordrb/api/server' require 'discordrb/api/invite' require 'discordrb/api/user' require 'time' require 'base64' # Discordrb module module Discordrb # The unix timestamp Discord IDs are based on DISCORD_EPOCH = 1_420_070_400_000 # Compares two objects based on IDs - either the objects' IDs are equal, or one object is equal to the other's ID. def self.id_compare(one_id, other) other.respond_to?(:resolve_id) ? (one_id.resolve_id == other.resolve_id) : (one_id == other) end # The maximum length a Discord message can have CHARACTER_LIMIT = 2000 # Splits a message into chunks of 2000 characters. Attempts to split by lines if possible. # @param msg [String] The message to split. # @return [Array<String>] the message split into chunks def self.split_message(msg) # If the messages is empty, return an empty array return [] if msg.empty? # Split the message into lines lines = msg.lines # Turn the message into a "triangle" of consecutively longer slices, for example the array [1,2,3,4] would become # [ # [1], # [1, 2], # [1, 2, 3], # [1, 2, 3, 4] # ] tri = [*0..(lines.length - 1)].map { |i| lines.combination(i + 1).first } # Join the individual elements together to get an array of strings with consecutively more lines joined = tri.map(&:join) # Find the largest element that is still below the character limit, or if none such element exists return the first ideal = joined.max_by { |e| e.length > CHARACTER_LIMIT ? -1 : e.length } # If it's still larger than the character limit (none was smaller than it) split it into slices with the length # being the character limit, otherwise just return an array with one element ideal_ary = ideal.length > CHARACTER_LIMIT ? ideal.chars.each_slice(CHARACTER_LIMIT).map(&:join) : [ideal] # Slice off the ideal part and strip newlines rest = msg[ideal.length..-1].strip # If none remains, return an empty array -> we're done return [] unless rest # Otherwise, call the method recursively to split the rest of the string and add it onto the ideal array ideal_ary + split_message(rest) end # Mixin for objects that have IDs module IDObject # @return [Integer] the ID which uniquely identifies this object across Discord. attr_reader :id alias_method :resolve_id, :id # ID based comparison def ==(other) Discordrb.id_compare(@id, other) end # Estimates the time this object was generated on based on the beginning of the ID. This is fairly accurate but # shouldn't be relied on as Discord might change its algorithm at any time # @return [Time] when this object was created at def creation_time # Milliseconds ms = (@id >> 22) + DISCORD_EPOCH Time.at(ms / 1000.0) end end # Mixin for the attributes users should have module UserAttributes # @return [String] this user's username attr_reader :username alias_method :name, :username # @return [String] this user's discriminator which is used internally to identify users with identical usernames. attr_reader :discriminator alias_method :discrim, :discriminator alias_method :tag, :discriminator alias_method :discord_tag, :discriminator # @return [true, false] whether this user is a Discord bot account attr_reader :bot_account alias_method :bot_account?, :bot_account # @return [String] the ID of this user's current avatar, can be used to generate an avatar URL. # @see #avatar_url attr_reader :avatar_id # Utility function to mention users in messages # @return [String] the mention code in the form of <@id> def mention "<@#{@id}>" end # Utility function to get Discord's distinct representation of a user, i. e. username + discriminator # @return [String] distinct representation of user def distinct "#{@username}##{@discriminator}" end # Utility function to get a user's avatar URL. # @return [String] the URL to the avatar image. def avatar_url API::User.avatar_url(@id, @avatar_id) end end # User on Discord, including internal data like discriminators class User include IDObject include UserAttributes # @!attribute [r] status # @return [Symbol] the current online status of the user (`:online`, `:offline` or `:idle`) attr_accessor :status # @!attribute [r] game # @return [String, nil] the game the user is currently playing, or `nil` if none is being played. attr_accessor :game def initialize(data, bot) @bot = bot @username = data['username'] @id = data['id'].to_i @discriminator = data['discriminator'] @avatar_id = data['avatar'] @roles = {} @bot_account = false @bot_account = true if data['bot'] @status = :offline end # Get a user's PM channel or send them a PM # @overload pm # Creates a private message channel for this user or returns an existing one if it already exists # @return [Channel] the PM channel to this user. # @overload pm(content) # Sends a private to this user. # @param content [String] The content to send. # @return [Message] the message sent to this user. def pm(content = nil) if content # Recursively call pm to get the channel, then send a message to it channel = pm channel.send_message(content) else # If no message was specified, return the PM channel @bot.pm_channel(@id) end end alias_method :dm, :pm # Send the user a file. # @param file [File] The file to send to the user # @param caption [String] The caption of the file being sent # @return [Message] the message sent to this user. def send_file(file, caption = nil) pm.send_file(file, caption: caption) end # Set the user's name # @note for internal use only # @!visibility private def update_username(username) @username = username end # Add an await for a message from this user. Specifically, this adds a global await for a MessageEvent with this # user's ID as a :from attribute. # @see Bot#add_await def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { from: @id }.merge(attributes), &block) end # Gets the member this user is on a server # @param server [Server] The server to get the member for # @return [Member] this user as a member on a particular server def on(server) id = server.resolve_id @bot.server(id).member(@id) end # Is the user the bot? # @return [true, false] whether this user is the bot def current_bot? @bot.profile.id == @id end # @return [true, false] whether this user is a fake user for a webhook message def webhook? @discriminator == Message::ZERO_DISCRIM end [:offline, :idle, :online].each do |e| define_method(e.to_s + '?') do @status.to_sym == e end end # The inspect method is overwritten to give more useful output def inspect "<User username=#{@username} id=#{@id} discriminator=#{@discriminator}>" end end # OAuth Application information class Application include IDObject # @return [String] the application name attr_reader :name # @return [String] the application description attr_reader :description # @return [Array<String>] the applications origins permitted to use RPC attr_reader :rpc_origins # @return [Integer] attr_reader :flags # Gets the user object of the owner. May be limited to username, discriminator, # ID and avatar if the bot cannot reach the owner. # @return [User] the user object of the owner attr_reader :owner def initialize(data, bot) @bot = bot @name = data['name'] @id = data['id'].to_i @description = data['description'] @icon_id = data['icon'] @rpc_origins = data['rpc_origins'] @flags = data['flags'] @owner = @bot.ensure_user(data['owner']) end # Utility function to get a application's icon URL. # @return [String, nil] the URL to the icon image (nil if no image is set). def icon_url return nil if @icon_id.nil? API.app_icon_url(@id, @icon_id) end # The inspect method is overwritten to give more useful output def inspect "<Application name=#{@name} id=#{@id}>" end end # Mixin for the attributes members and private members should have module MemberAttributes # @return [Time] when this member joined the server. attr_reader :joined_at # @return [String, nil] the nickname this member has, or nil if it has none. attr_reader :nick alias_method :nickname, :nick # @return [Array<Role>] the roles this member has. attr_reader :roles # @return [Server] the server this member is on. attr_reader :server end # Mixin to calculate resulting permissions from overrides etc. module PermissionCalculator # Checks whether this user can do the particular action, regardless of whether it has the permission defined, # through for example being the server owner or having the Manage Roles permission # @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list. # @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked. # @example Check if the bot can send messages to a specific channel in a server. # bot_profile = bot.profile.on(event.server) # can_send_messages = bot_profile.permission?(:send_messages, channel) # @return [true, false] whether or not this user has the permission. def permission?(action, channel = nil) # If the member is the server owner, it irrevocably has all permissions. return true if owner? # First, check whether the user has Manage Roles defined. # (Coincidentally, Manage Permissions is the same permission as Manage Roles, and a # Manage Permissions deny overwrite will override Manage Roles, so we can just check for # Manage Roles once and call it a day.) return true if defined_permission?(:administrator, channel) # Otherwise, defer to defined_permission defined_permission?(action, channel) end # Checks whether this user has a particular permission defined (i. e. not implicit, through for example # Manage Roles) # @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list. # @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked. # @example Check if a member has the Manage Channels permission defined in the server. # has_manage_channels = member.defined_permission?(:manage_channels) # @return [true, false] whether or not this user has the permission defined. def defined_permission?(action, channel = nil) # Get the permission the user's roles have role_permission = defined_role_permission?(action, channel) # Once we have checked the role permission, we have to check the channel overrides for the # specific user user_specific_override = permission_overwrite(action, channel, id) # Use the ID reader as members have no ID instance variable # Merge the two permissions - if an override is defined, it has to be allow, otherwise we only care about the role return role_permission unless user_specific_override user_specific_override == :allow end # Define methods for querying permissions Discordrb::Permissions::Flags.each_value do |flag| define_method "can_#{flag}?" do |channel = nil| permission? flag, channel end end alias_method :can_administrate?, :can_administrator? private def defined_role_permission?(action, channel) # For each role, check if # (1) the channel explicitly allows or permits an action for the role and # (2) if the user is allowed to do the action if the channel doesn't specify @roles.reduce(false) do |can_act, role| # Get the override defined for the role on the channel channel_allow = permission_overwrite(action, channel, role.id) can_act = if channel_allow # If the channel has an override, check whether it is an allow - if yes, # the user can act, if not, it can't channel_allow == :allow else # Otherwise defer to the role role.permissions.instance_variable_get("@#{action}") || can_act end can_act end end def permission_overwrite(action, channel, id) # If no overwrites are defined, or no channel is set, no overwrite will be present return nil unless channel && channel.permission_overwrites[id] # Otherwise, check the allow and deny objects allow = channel.permission_overwrites[id].allow deny = channel.permission_overwrites[id].deny if allow.instance_variable_get("@#{action}") :allow elsif deny.instance_variable_get("@#{action}") :deny end # If there's no variable defined, nil will implicitly be returned end end # A voice state represents the state of a member's connection to a voice channel. It includes data like the voice # channel the member is connected to and mute/deaf flags. class VoiceState # @return [Integer] the ID of the user whose voice state is represented by this object. attr_reader :user_id # @return [true, false] whether this voice state's member is muted server-wide. attr_reader :mute # @return [true, false] whether this voice state's member is deafened server-wide. attr_reader :deaf # @return [true, false] whether this voice state's member has muted themselves. attr_reader :self_mute # @return [true, false] whether this voice state's member has deafened themselves. attr_reader :self_deaf # @return [Channel] the voice channel this voice state's member is in. attr_reader :voice_channel # @!visibility private def initialize(user_id) @user_id = user_id end # Update this voice state with new data from Discord # @note For internal use only. # @!visibility private def update(channel, mute, deaf, self_mute, self_deaf) @voice_channel = channel @mute = mute @deaf = deaf @self_mute = self_mute @self_deaf = self_deaf end end # A member is a user on a server. It differs from regular users in that it has roles, voice statuses and things like # that. class Member < DelegateClass(User) # @return [true, false] whether this member is muted server-wide. def mute voice_state_attribute(:mute) end # @return [true, false] whether this member is deafened server-wide. def deaf voice_state_attribute(:deaf) end # @return [true, false] whether this member has muted themselves. def self_mute voice_state_attribute(:self_mute) end # @return [true, false] whether this member has deafened themselves. def self_deaf voice_state_attribute(:self_deaf) end # @return [Channel] the voice channel this member is in. def voice_channel voice_state_attribute(:voice_channel) end alias_method :muted?, :mute alias_method :deafened?, :deaf alias_method :self_muted?, :self_mute alias_method :self_deafened?, :self_deaf include MemberAttributes # @!visibility private def initialize(data, server, bot) @bot = bot @user = bot.ensure_user(data['user']) super @user # Initialize the delegate class # Somehow, Discord doesn't send the server ID in the standard member format... raise ArgumentError, 'Cannot create a member without any information about the server!' if server.nil? && data['guild_id'].nil? @server = server || bot.server(data['guild_id'].to_i) # Initialize the roles by getting the roles from the server one-by-one update_roles(data['roles']) @nick = data['nick'] @joined_at = data['joined_at'] ? Time.parse(data['joined_at']) : nil end # @return [true, false] whether this member is the server owner. def owner? @server.owner == self end # @param role [Role, Integer, #resolve_id] the role to check or its ID. # @return [true, false] whether this member has the specified role. def role?(role) role = role.resolve_id @roles.any? { |e| e.id == role } end # Bulk sets a member's roles. # @param role [Role, Array<Role>] The role(s) to set. def roles=(role) role_ids = role_id_array(role) API::Server.update_member(@bot.token, @server.id, @user.id, roles: role_ids) end # Adds and removes roles from a member. # @param add [Role, Array<Role>] The role(s) to add. # @param remove [Role, Array<Role>] The role(s) to remove. # @example Remove the 'Member' role from a user, and add the 'Muted' role to them. # to_add = server.roles.find {|role| role.name == 'Muted'} # to_remove = server.roles.find {|role| role.name == 'Member'} # member.modify_roles(to_add, to_remove) def modify_roles(add, remove) add_role_ids = role_id_array(add) remove_role_ids = role_id_array(remove) old_role_ids = @roles.map(&:id) new_role_ids = (old_role_ids - remove_role_ids + add_role_ids).uniq API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids) end # Adds one or more roles to this member. # @param role [Role, Array<Role>] The role(s) to add. def add_role(role) role_ids = role_id_array(role) old_role_ids = @roles.map(&:id) new_role_ids = (old_role_ids + role_ids).uniq API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids) end # Removes one or more roles from this member. # @param role [Role, Array<Role>] The role(s) to remove. def remove_role(role) old_role_ids = @roles.map(&:id) role_ids = role_id_array(role) new_role_ids = old_role_ids.reject { |i| role_ids.include?(i) } API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids) end # Server deafens this member. def server_deafen API::Server.update_member(@bot.token, @server.id, @user.id, deaf: true) end # Server undeafens this member. def server_undeafen API::Server.update_member(@bot.token, @server.id, @user.id, deaf: false) end # Server mutes this member. def server_mute API::Server.update_member(@bot.token, @server.id, @user.id, mute: true) end # Server unmutes this member. def server_unmute API::Server.update_member(@bot.token, @server.id, @user.id, mute: false) end # Sets or resets this member's nickname. Requires the Change Nickname permission for the bot itself and Manage # Nicknames for other users. # @param nick [String, nil] The string to set the nickname to, or nil if it should be reset. def nick=(nick) # Discord uses the empty string to signify 'no nickname' so we convert nil into that nick ||= '' if @user.current_bot? API::User.change_own_nickname(@bot.token, @server.id, nick) else API::Server.update_member(@bot.token, @server.id, @user.id, nick: nick) end end alias_method :nickname=, :nick= # @return [String] the name the user displays as (nickname if they have one, username otherwise) def display_name nickname || username end # Update this member's roles # @note For internal use only. # @!visibility private def update_roles(roles) @roles = roles.map do |role| role.is_a?(Role) ? role : @server.role(role.to_i) end end # Update this member's nick # @note For internal use only. # @!visibility private def update_nick(nick) @nick = nick end include PermissionCalculator # Overwriting inspect for debug purposes def inspect "<Member user=#{@user.inspect} server=#{@server.inspect} joined_at=#{@joined_at} roles=#{@roles.inspect} voice_channel=#{@voice_channel.inspect} mute=#{@mute} deaf=#{@deaf} self_mute=#{@self_mute} self_deaf=#{@self_deaf}>" end private # Utility method to get a list of role IDs from one role or an array of roles def role_id_array(role) if role.is_a? Array role.map(&:resolve_id) else [role.resolve_id] end end # Utility method to get data out of this member's voice state def voice_state_attribute(name) voice_state = @server.voice_states[@user.id] voice_state.send name if voice_state end end # Recipients are members on private channels - they exist for completeness purposes, but all # the attributes will be empty. class Recipient < DelegateClass(User) include MemberAttributes # @return [Channel] the private channel this recipient is the recipient of. attr_reader :channel # @!visibility private def initialize(user, channel, bot) @bot = bot @channel = channel raise ArgumentError, 'Tried to create a recipient for a public channel!' unless @channel.private? @user = user super @user # Member attributes @mute = @deaf = @self_mute = @self_deaf = false @voice_channel = nil @server = nil @roles = [] @joined_at = @channel.creation_time end # Overwriting inspect for debug purposes def inspect "<Recipient user=#{@user.inspect} channel=#{@channel.inspect}>" end end # This class is a special variant of User that represents the bot's user profile (things like own username and the avatar). # It can be accessed using {Bot#profile}. class Profile < User def initialize(data, bot) super(data, bot) end # Whether or not the user is the bot. The Profile can only ever be the bot user, so this always returns true. # @return [true] def current_bot? true end # Sets the bot's username. # @param username [String] The new username. def username=(username) update_profile_data(username: username) end alias_method :name=, :username= # Changes the bot's avatar. # @param avatar [String, #read] A JPG file to be used as the avatar, either # something readable (e. g. File Object) or as a data URL. def avatar=(avatar) if avatar.respond_to? :read # Set the file to binary mode if supported, so we don't get problems with Windows avatar.binmode if avatar.respond_to?(:binmode) avatar_string = 'data:image/jpg;base64,' avatar_string += Base64.strict_encode64(avatar.read) update_profile_data(avatar: avatar_string) else update_profile_data(avatar: avatar) end end # Updates the cached profile data with the new one. # @note For internal use only. # @!visibility private def update_data(new_data) @username = new_data[:username] || @username @avatar_id = new_data[:avatar_id] || @avatar_id end # Sets the user status setting to Online. # @note Only usable on User accounts. def online update_profile_status_setting('online') end # Sets the user status setting to Idle. # @note Only usable on User accounts. def idle update_profile_status_setting('idle') end # Sets the user status setting to Do Not Disturb. # @note Only usable on User accounts. def dnd update_profile_status_setting('dnd') end alias_method(:busy, :dnd) # Sets the user status setting to Invisible. # @note Only usable on User accounts. def invisible update_profile_status_setting('invisible') end # The inspect method is overwritten to give more useful output def inspect "<Profile user=#{super}>" end private # Internal handler for updating the user's status setting def update_profile_status_setting(status) API::User.change_status_setting(@bot.token, status) end def update_profile_data(new_data) API::User.update_profile(@bot.token, nil, nil, new_data[:username] || @username, new_data.key?(:avatar) ? new_data[:avatar] : @avatar_id) update_data(new_data) end end # A Discord role that contains permissions and applies to certain users class Role include IDObject # @return [Permissions] this role's permissions. attr_reader :permissions # @return [String] this role's name ("new role" if it hasn't been changed) attr_reader :name # @return [true, false] whether or not this role should be displayed separately from other users attr_reader :hoist # @return [true, false] whether this role can be mentioned using a role mention attr_reader :mentionable alias_method :mentionable?, :mentionable # @return [ColourRGB] the role colour attr_reader :colour alias_method :color, :colour # @return [Integer] the position of this role in the hierarchy attr_reader :position # This class is used internally as a wrapper to a Role object that allows easy writing of permission data. class RoleWriter # @!visibility private def initialize(role, token) @role = role @token = token end # Write the specified permission data to the role, without updating the permission cache # @param bits [Integer] The packed permissions to write. def write(bits) @role.send(:packed=, bits, false) end # The inspect method is overridden, in this case to prevent the token being leaked def inspect "<RoleWriter role=#{@role} token=...>" end end # @!visibility private def initialize(data, bot, server = nil) @bot = bot @server = server @permissions = Permissions.new(data['permissions'], RoleWriter.new(self, @bot.token)) @name = data['name'] @id = data['id'].to_i @position = data['position'] @hoist = data['hoist'] @mentionable = data['mentionable'] @colour = ColourRGB.new(data['color']) end # @return [String] a string that will mention this role, if it is mentionable. def mention "<@&#{@id}>" end # @return [Array<Member>] an array of members who have this role. # @note This requests a member chunk if it hasn't for the server before, which may be slow initially def members @server.members.select { |m| m.role? role } end alias_method :users, :members # Updates the data cache from another Role object # @note For internal use only # @!visibility private def update_from(other) @permissions = other.permissions @name = other.name @hoist = other.hoist @colour = other.colour @position = other.position end # Updates the data cache from a hash containing data # @note For internal use only # @!visibility private def update_data(new_data) @name = new_data[:name] || new_data['name'] || @name @hoist = new_data['hoist'] unless new_data['hoist'].nil? @hoist = new_data[:hoist] unless new_data[:hoist].nil? @colour = new_data[:colour] || (new_data['color'] ? ColourRGB.new(new_data['color']) : @colour) end # Sets the role name to something new # @param name [String] The name that should be set def name=(name) update_role_data(name: name) end # Changes whether or not this role is displayed at the top of the user list # @param hoist [true, false] The value it should be changed to def hoist=(hoist) update_role_data(hoist: hoist) end # Changes whether or not this role can be mentioned # @param mentionable [true, false] The value it should be changed to def mentionable=(mentionable) update_role_data(mentionable: mentionable) end # Sets the role colour to something new # @param colour [ColourRGB] The new colour def colour=(colour) update_role_data(colour: colour) end alias_method :color=, :colour= # Changes this role's permissions to a fixed bitfield. This allows setting multiple permissions at once with just # one API call. # # Information on how this bitfield is structured can be found at # https://discordapp.com/developers/docs/topics/permissions. # @example Remove all permissions from a role # role.packed = 0 # @param packed [Integer] A bitfield with the desired permissions value. # @param update_perms [true, false] Whether the internal data should also be updated. This should always be true # when calling externally. def packed=(packed, update_perms = true) update_role_data(permissions: packed) @permissions.bits = packed if update_perms end # Deletes this role. This cannot be undone without recreating the role! def delete API::Server.delete_role(@bot.token, @server.id, @id) @server.delete_role(@id) end # The inspect method is overwritten to give more useful output def inspect "<Role name=#{@name} permissions=#{@permissions.inspect} hoist=#{@hoist} colour=#{@colour.inspect} server=#{@server.inspect}>" end private def update_role_data(new_data) API::Server.update_role(@bot.token, @server.id, @id, new_data[:name] || @name, (new_data[:colour] || @colour).combined, new_data[:hoist].nil? ? @hoist : new_data[:hoist], new_data[:mentionable].nil? ? @mentionable : new_data[:mentionable], new_data[:permissions] || @permissions.bits) update_data(new_data) end end # A channel referenced by an invite. It has less data than regular channels, so it's a separate class class InviteChannel include IDObject # @return [String] this channel's name. attr_reader :name # @return [Integer] this channel's type (0: text, 1: private, 2: voice, 3: group). attr_reader :type # @!visibility private def initialize(data, bot) @bot = bot @id = data['id'].to_i @name = data['name'] @type = data['type'] end end # A server referenced to by an invite class InviteServer include IDObject # @return [String] this server's name. attr_reader :name # @return [String, nil] the hash of the server's invite splash screen (for partnered servers) or nil if none is # present attr_reader :splash_hash # @!visibility private def initialize(data, bot) @bot = bot @id = data['id'].to_i @name = data['name'] @splash_hash = data['splash_hash'] end end # A Discord invite to a channel class Invite # @return [InviteChannel] the channel this invite references. attr_reader :channel # @return [InviteServer] the server this invite references. attr_reader :server # @return [Integer] the amount of uses left on this invite. attr_reader :uses alias_method :max_uses, :uses # @return [User, nil] the user that made this invite. May also be nil if the user can't be determined. attr_reader :inviter alias_method :user, :inviter # @return [true, false] whether or not this invite is temporary. attr_reader :temporary alias_method :temporary?, :temporary # @return [true, false] whether this invite is still valid. attr_reader :revoked alias_method :revoked?, :revoked # @return [String] this invite's code attr_reader :code # @!visibility private def initialize(data, bot) @bot = bot @channel = InviteChannel.new(data['channel'], bot) @server = InviteServer.new(data['guild'], bot) @uses = data['uses'] @inviter = data['inviter'] ? (@bot.user(data['inviter']['id'].to_i) || User.new(data['inviter'], bot)) : nil @temporary = data['temporary'] @revoked = data['revoked'] @code = data['code'] end # Code based comparison def ==(other) other.respond_to?(:code) ? (@code == other.code) : (@code == other) end # Deletes this invite def delete API::Invite.delete(@bot.token, @code) end alias_method :revoke, :delete # The inspect method is overwritten to give more useful output def inspect "<Invite code=#{@code} channel=#{@channel} uses=#{@uses} temporary=#{@temporary} revoked=#{@revoked}>" end # Creates an invite URL. def url "https://discord.gg/#{@code}" end end # A Discord channel, including data like the topic class Channel include IDObject # @return [String] this channel's name. attr_reader :name # @return [Server, nil] the server this channel is on. If this channel is a PM channel, it will be nil. attr_reader :server # @return [Integer] the type of this channel (0: text, 1: private, 2: voice, 3: group) attr_reader :type # @return [Integer, nil] the id of the owner of the group channel or nil if this is not a group channel. attr_reader :owner_id # @return [Array<Recipient>, nil] the array of recipients of the private messages, or nil if this is not a Private channel attr_reader :recipients # @return [String] the channel's topic attr_reader :topic # @return [Integer] the bitrate (in bps) of the channel attr_reader :bitrate # @return [Integer] the amount of users that can be in the channel. `0` means it is unlimited. attr_reader :user_limit alias_method :limit, :user_limit # @return [Integer] the channel's position on the channel list attr_reader :position # This channel's permission overwrites, represented as a hash of role/user ID to an OpenStruct which has the # `allow` and `deny` properties which are {Permissions} objects respectively. # @return [Hash<Integer => OpenStruct>] the channel's permission overwrites attr_reader :permission_overwrites # @return [true, false] whether or not this channel is a PM or group channel. def private? pm? || group? end # @return [String] a string that will mention the channel as a clickable link on Discord. def mention "<##{@id}>" end # @return [Recipient, nil] the recipient of the private messages, or nil if this is not a PM channel def recipient @recipients.first if pm? end # @!visibility private def initialize(data, bot, server = nil) @bot = bot # data is a sometimes a Hash and other times an array of Hashes, you only want the last one if it's an array data = data[-1] if data.is_a?(Array) @id = data['id'].to_i @type = data['type'] || 0 @topic = data['topic'] @bitrate = data['bitrate'] @user_limit = data['user_limit'] @position = data['position'] if private? @recipients = [] if data['recipients'] data['recipients'].each do |recipient| recipient_user = bot.ensure_user(recipient) @recipients << Recipient.new(recipient_user, self, bot) end end if pm? @name = @recipients.first.username else @name = data['name'] @owner_id = data['owner_id'] end else @name = data['name'] @server = if server server else bot.server(data['guild_id'].to_i) end end # Populate permission overwrites @permission_overwrites = {} return unless data['permission_overwrites'] data['permission_overwrites'].each do |element| role_id = element['id'].to_i deny = Permissions.new(element['deny']) allow = Permissions.new(element['allow']) @permission_overwrites[role_id] = OpenStruct.new @permission_overwrites[role_id].deny = deny @permission_overwrites[role_id].allow = allow end end # @return [true, false] whether or not this channel is a text channel def text? @type.zero? end # @return [true, false] whether or not this channel is a PM channel. def pm? @type == 1 end # @return [true, false] whether or not this channel is a voice channel. def voice? @type == 2 end # @return [true, false] whether or not this channel is a group channel. def group? @type == 3 end # Sends a message to this channel. # @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error. # @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech. # @return [Message] the message that was sent. def send_message(content, tts = false) @bot.send_message(@id, content, tts, @server && @server.id) end alias_method :send, :send_message # Sends a temporary message to this channel. # @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error. # @param timeout [Float] The amount of time in seconds after which the message sent will be deleted. # @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech. def send_temporary_message(content, timeout, tts = false) @bot.send_temporary_message(@id, content, timeout, tts, @server && @server.id) end # Sends multiple messages to a channel # @param content [Array<String>] The messages to send. def send_multiple(content) content.each { |e| send_message(e) } end # Splits a message into chunks whose length is at most the Discord character limit, then sends them individually. # Useful for sending long messages, but be wary of rate limits! def split_send(content) send_multiple(Discordrb.split_message(content)) end # Sends a file to this channel. If it is an image, it will be embedded. # @param file [File] The file to send. There's no clear size limit for this, you'll have to attempt it for yourself (most non-image files are fine, large images may fail to embed) # @param caption [string] The caption for the file. # @param tts [true, false] Whether or not this file's caption should be sent using Discord text-to-speech. def send_file(file, caption: nil, tts: false) @bot.send_file(@id, file, caption: caption, tts: tts) end # Permanently deletes this channel def delete API::Channel.delete(@bot.token, @id) end # Sets this channel's name. The name must be alphanumeric with dashes, unless this is a voice channel (then there are no limitations) # @param name [String] The new name. def name=(name) @name = name update_channel_data end # Sets this channel's topic. # @param topic [String] The new topic. def topic=(topic) raise 'Tried to set topic on voice channel' if voice? @topic = topic update_channel_data end # Sets this channel's bitrate. # @param bitrate [Integer] The new bitrate (in bps). Number has to be between 8000-96000 (128000 for VIP servers) def bitrate=(bitrate) raise 'Tried to set bitrate on text channel' if text? @bitrate = bitrate update_channel_data end # Sets this channel's user limit. # @param limit [Integer] The new user limit. `0` for unlimited, has to be a number between 0-99 def user_limit=(limit) raise 'Tried to set user_limit on text channel' if text? @user_limit = limit update_channel_data end alias_method :limit=, :user_limit= # Sets this channel's position in the list. # @param position [Integer] The new position. def position=(position) @position = position update_channel_data end # Defines a permission overwrite for this channel that sets the specified thing to the specified allow and deny # permission sets, or change an existing one. # @param thing [User, Role] What to define an overwrite for. # @param allow [#bits, Permissions, Integer] The permission sets that should receive an `allow` override (i. e. a # green checkmark on Discord) # @param deny [#bits, Permissions, Integer] The permission sets that should receive a `deny` override (i. e. a red # cross on Discord) # @example Define a permission overwrite for a user that can then mention everyone and use TTS, but not create any invites # allow = Discordrb::Permissions.new # allow.can_mention_everyone = true # allow.can_send_tts_messages = true # # deny = Discordrb::Permissions.new # deny.can_create_instant_invite = true # # channel.define_overwrite(user, allow, deny) def define_overwrite(thing, allow, deny) allow_bits = allow.respond_to?(:bits) ? allow.bits : allow deny_bits = deny.respond_to?(:bits) ? deny.bits : deny type = if thing.is_a?(User) || thing.is_a?(Member) || thing.is_a?(Recipient) || thing.is_a?(Profile) :member elsif thing.is_a? Role :role else raise ArgumentError, '`thing` in define_overwrite needs to be a kind of User (User, Member, Recipient, Profile) or a Role!' end API::Channel.update_permission(@bot.token, @id, thing.id, allow_bits, deny_bits, type) end # Updates the cached data from another channel. # @note For internal use only # @!visibility private def update_from(other) @topic = other.topic @name = other.name @permission_overwrites = other.permission_overwrites end # The list of users currently in this channel. For a voice channel, it will return all the members currently # in that channel. For a text channel, it will return all online members that have permission to read it. # @return [Array<Member>] the users in this channel def users if text? @server.online_members(include_idle: true).select { |u| u.can_read_messages? self } elsif voice? @server.voice_states.map { |id, voice_state| @server.member(id) if !voice_state.voice_channel.nil? && voice_state.voice_channel.id == @id }.compact end end # Retrieves some of this channel's message history. # @param amount [Integer] How many messages to retrieve. This must be less than or equal to 100, if it is higher # than 100 it will be treated as 100 on Discord's side. # @param before_id [Integer] The ID of the most recent message the retrieval should start at, or nil if it should # start at the current message. # @param after_id [Integer] The ID of the oldest message the retrieval should start at, or nil if it should start # as soon as possible with the specified amount. # @example Count the number of messages in the last 50 messages that contain the letter 'e'. # message_count = channel.history(50).count {|message| message.content.include? "e"} # @return [Array<Message>] the retrieved messages. def history(amount, before_id = nil, after_id = nil) logs = API::Channel.messages(@bot.token, @id, amount, before_id, after_id) JSON.parse(logs).map { |message| Message.new(message, @bot) } end # Retrieves message history, but only message IDs for use with prune # @note For internal use only # @!visibility private def history_ids(amount, before_id = nil, after_id = nil) logs = API::Channel.messages(@bot.token, @id, amount, before_id, after_id) JSON.parse(logs).map { |message| message['id'] } end # Returns a single message from this channel's history by ID. # @param message_id [Integer] The ID of the message to retrieve. # @return [Message] the retrieved message. def load_message(message_id) response = API::Channel.message(@bot.token, @id, message_id) return Message.new(JSON.parse(response), @bot) rescue RestClient::ResourceNotFound return nil end alias_method :message, :load_message # Requests all pinned messages of a channel. # @return [Array<Message>] the received messages. def pins msgs = API::Channel.pinned_messages(@bot.token, @id) JSON.parse(msgs).map { |msg| Message.new(msg, @bot) } end # Delete the last N messages on this channel. # @param amount [Integer] How many messages to delete. Must be a value between 2 and 100 (Discord limitation) # @raise [ArgumentError] if the amount of messages is not a value between 2 and 100 def prune(amount) raise ArgumentError, 'Can only prune between 2 and 100 messages!' unless amount.between?(2, 100) messages = history_ids(amount) API::Channel.bulk_delete_messages(@bot.token, @id, messages) end # Deletes a collection of messages # @param messages [Array<Message, Integer>] the messages (or message IDs) to delete. Total must be an amount between 2 and 100 (Discord limitation) # @raise [ArgumentError] if the amount of messages is not a value between 2 and 100 def delete_messages(messages) raise ArgumentError, 'Can only delete between 2 and 100 messages!' unless messages.count.between?(2, 100) messages.map!(&:resolve_id) API::Channel.bulk_delete_messages(@bot.token, @id, messages) end # Updates the cached permission overwrites # @note For internal use only # @!visibility private def update_overwrites(overwrites) @permission_overwrites = overwrites end # Add an {Await} for a message in this channel. This is identical in functionality to adding a # {Discordrb::Events::MessageEvent} await with the `in` attribute as this channel. # @see Bot#add_await def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { in: @id }.merge(attributes), &block) end # Creates a new invite to this channel. # @param max_age [Integer] How many seconds this invite should last. # @param max_uses [Integer] How many times this invite should be able to be used. # @param temporary [true, false] Whether membership should be temporary (kicked after going offline). # @return [Invite] the created invite. def make_invite(max_age = 0, max_uses = 0, temporary = false) response = API::Channel.create_invite(@bot.token, @id, max_age, max_uses, temporary) Invite.new(JSON.parse(response), @bot) end alias_method :invite, :make_invite # Starts typing, which displays the typing indicator on the client for five seconds. # If you want to keep typing you'll have to resend this every five seconds. (An abstraction # for this will eventually be coming) def start_typing API::Channel.start_typing(@bot.token, @id) end # Creates a Group channel # @param user_ids [Array<Integer>] Array of user IDs to add to the new group channel (Excluding # the recipient of the PM channel). # @return [Channel] the created channel. def create_group(user_ids) raise 'Attempted to create group channel on a non-pm channel!' unless pm? response = API::Channel.create_group(@bot.token, @id, user_ids.shift) channel = Channel.new(JSON.parse(response), @bot) channel.add_group_users(user_ids) end # Adds a user to a Group channel # @param user_ids [Array<#resolve_id>, #resolve_id] User ID or array of user IDs to add to the group channel. # @return [Channel] the group channel. def add_group_users(user_ids) raise 'Attempted to add a user to a non-group channel!' unless group? user_ids = [user_ids] unless user_ids.is_a? Array user_ids.each do |user_id| API::Channel.add_group_user(@bot.token, @id, user_id.resolve_id) end self end alias_method :add_group_user, :add_group_users # Removes a user from a group channel. # @param user_ids [Array<#resolve_id>, #resolve_id] User ID or array of user IDs to remove from the group channel. # @return [Channel] the group channel. def remove_group_users(user_ids) raise 'Attempted to remove a user from a non-group channel!' unless group? user_ids = [user_ids] unless user_ids.is_a? Array user_ids.each do |user_id| API::Channel.remove_group_user(@bot.token, @id, user_id.resolve_id) end self end alias_method :remove_group_user, :remove_group_users # Leaves the group def leave_group raise 'Attempted to leave a non-group channel!' unless group? API::Channel.leave_group(@bot.token, @id) end alias_method :leave, :leave_group # The inspect method is overwritten to give more useful output def inspect "<Channel name=#{@name} id=#{@id} topic=\"#{@topic}\" type=#{@type} position=#{@position} server=#{@server}>" end # Adds a recipient to a group channel. # @param recipient [Recipient] the recipient to add to the group # @raise [ArgumentError] if tried to add a non-recipient # @note For internal use only # @!visibility private def add_recipient(recipient) raise 'Tried to add recipient to a non-group channel' unless group? raise ArgumentError, 'Tried to add a non-recipient to a group' unless recipient.is_a?(Recipient) @recipients << recipient end # Removes a recipient from a group channel. # @param recipient [Recipient] the recipient to remove from the group # @raise [ArgumentError] if tried to remove a non-recipient # @note For internal use only # @!visibility private def remove_recipient(recipient) raise 'Tried to add recipient to a non-group channel' unless group? raise ArgumentError, 'Tried to remove a non-recipient from a group' unless recipient.is_a?(Recipient) @recipients.delete(recipient) end private def update_channel_data API::Channel.update(@bot.token, @id, @name, @topic, @position, @bitrate, @user_limit) end end # An Embed object that is contained in a message # A freshly generated embed object will not appear in a message object # unless grabbed from its ID in a channel. class Embed # @return [Message] the message this embed object is contained in. attr_reader :message # @return [String] the URL this embed object is based on. attr_reader :url # @return [String, nil] the title of the embed object. `nil` if there is not a title attr_reader :title # @return [String, nil] the description of the embed object. `nil` if there is not a description attr_reader :description # @return [Symbol] the type of the embed object. Possible types are: # # * `:link` # * `:video` # * `:image` attr_reader :type # @return [EmbedProvider, nil] the provider of the embed object. `nil` is there is not a provider attr_reader :provider # @return [EmbedThumbnail, nil] the thumbnail of the embed object. `nil` is there is not a thumbnail attr_reader :thumbnail # @return [EmbedAuthor, nil] the author of the embed object. `nil` is there is not an author attr_reader :author # @!visibility private def initialize(data, message) @message = message @url = data['url'] @title = data['title'] @type = data['type'].to_sym @description = data['description'] @provider = data['provider'].nil? ? nil : EmbedProvider.new(data['provider'], self) @thumbnail = data['thumbnail'].nil? ? nil : EmbedThumbnail.new(data['thumbnail'], self) @author = data['author'].nil? ? nil : EmbedAuthor.new(data['author'], self) end end # An Embed thumbnail for the embed object class EmbedThumbnail # @return [Embed] the embed object this is based on. attr_reader :embed # @return [String] the CDN URL this thumbnail can be downloaded at. attr_reader :url # @return [String] the thumbnail's proxy URL - I'm not sure what exactly this does, but I think it has something to # do with CDNs attr_reader :proxy_url # @return [Integer] the width of this thumbnail file, in pixels. attr_reader :width # @return [Integer] the height of this thumbnail file, in pixels. attr_reader :height # @!visibility private def initialize(data, embed) @embed = embed @url = data['url'] @proxy_url = data['proxy_url'] @width = data['width'] @height = data['height'] end end # An Embed provider for the embed object class EmbedProvider # @return [Embed] the embed object this is based on. attr_reader :embed # @return [String] the provider's name. attr_reader :name # @return [String, nil] the URL of the provider. `nil` is there is no URL attr_reader :url # @!visibility private def initialize(data, embed) @embed = embed @name = data['name'] @url = data['url'] end end # An Embed author for the embed object class EmbedAuthor # @return [Embed] the embed object this is based on. attr_reader :embed # @return [String] the author's name. attr_reader :name # @return [String, nil] the URL of the author's website. `nil` is there is no URL attr_reader :url # @!visibility private def initialize(data, embed) @embed = embed @name = data['name'] @url = data['url'] end end # An attachment to a message class Attachment include IDObject # @return [Message] the message this attachment belongs to. attr_reader :message # @return [String] the CDN URL this attachment can be downloaded at. attr_reader :url # @return [String] the attachment's proxy URL - I'm not sure what exactly this does, but I think it has something to # do with CDNs attr_reader :proxy_url # @return [String] the attachment's filename. attr_reader :filename # @return [Integer] the attachment's file size in bytes. attr_reader :size # @return [Integer, nil] the width of an image file, in pixels, or nil if the file is not an image. attr_reader :width # @return [Integer, nil] the height of an image file, in pixels, or nil if the file is not an image. attr_reader :height # @!visibility private def initialize(data, message, bot) @bot = bot @message = message @url = data['url'] @proxy_url = data['proxy_url'] @filename = data['filename'] @size = data['size'] @width = data['width'] @height = data['height'] end # @return [true, false] whether this file is an image file. def image? !(@width.nil? || @height.nil?) end end # A message on Discord that was sent to a text channel class Message include IDObject # @return [String] the content of this message. attr_reader :content alias_method :text, :content alias_method :to_s, :content # @return [Member] the user that sent this message. attr_reader :author alias_method :user, :author alias_method :writer, :author # @return [Channel] the channel in which this message was sent. attr_reader :channel # @return [Time] the timestamp at which this message was sent. attr_reader :timestamp # @return [Time] the timestamp at which this message was edited. `nil` if the message was never edited. attr_reader :edited_timestamp alias_method :edit_timestamp, :edited_timestamp # @return [Array<User>] the users that were mentioned in this message. attr_reader :mentions # @return [Array<Role>] the roles that were mentioned in this message. attr_reader :role_mentions # @return [Array<Attachment>] the files attached to this message. attr_reader :attachments # @return [Array<Embed>] the embed objects contained in this message. attr_reader :embeds # @return [Array<Reaction>] the reaction objects attached to this message attr_reader :reactions # @return [true, false] whether the message used Text-To-Speech (TTS) or not. attr_reader :tts alias_method :tts?, :tts # @return [String] used for validating a message was sent attr_reader :nonce # @return [true, false] whether the message was edited or not. attr_reader :edited alias_method :edited?, :edited # @return [true, false] whether the message mentioned everyone or not. attr_reader :mention_everyone alias_method :mention_everyone?, :mention_everyone alias_method :mentions_everyone?, :mention_everyone # @return [true, false] whether the message is pinned or not. attr_reader :pinned alias_method :pinned?, :pinned # @return [Integer, nil] the webhook ID that sent this message, or nil if it wasn't sent through a webhook. attr_reader :webhook_id # The discriminator that webhook user accounts have. ZERO_DISCRIM = '0000'.freeze # @!visibility private def initialize(data, bot) @bot = bot @content = data['content'] @channel = bot.channel(data['channel_id'].to_i) @pinned = data['pinned'] @tts = data['tts'] @nonce = data['nonce'] @mention_everyone = data['mention_everyone'] @author = if data['author'] if data['author']['discriminator'] == ZERO_DISCRIM # This is a webhook user! It would be pointless to try to resolve a member here, so we just create # a User and return that instead. Discordrb::LOGGER.debug("Webhook user: #{data['author']['id']}") User.new(data['author'], @bot) elsif @channel.private? # Turn the message user into a recipient - we can't use the channel recipient # directly because the bot may also send messages to the channel Recipient.new(bot.user(data['author']['id'].to_i), @channel, bot) else member = @channel.server.member(data['author']['id'].to_i) Discordrb::LOGGER.warn("Member with ID #{data['author']['id']} not cached even though it should be.") unless member member end end @webhook_id = data['webhook_id'].to_i if data['webhook_id'] @timestamp = Time.parse(data['timestamp']) if data['timestamp'] @edited_timestamp = data['edited_timestamp'].nil? ? nil : Time.parse(data['edited_timestamp']) @edited = !@edited_timestamp.nil? @id = data['id'].to_i @emoji = [] @mentions = [] data['mentions'].each do |element| @mentions << bot.ensure_user(element) end if data['mentions'] @role_mentions = [] # Role mentions can only happen on public servers so make sure we only parse them there if @channel.text? data['mention_roles'].each do |element| @role_mentions << @channel.server.role(element.to_i) end if data['mention_roles'] end @attachments = [] @attachments = data['attachments'].map { |e| Attachment.new(e, self, @bot) } if data['attachments'] @embeds = [] @embeds = data['embeds'].map { |e| Embed.new(e, self) } if data['embeds'] @reactions = data['reactions'].map { |e| Reaction.new(e) } if data['reactions'] end # Replies to this message with the specified content. # @see Channel#send_message def reply(content) @channel.send_message(content) end # Edits this message to have the specified content instead. # You can only edit your own messages. # @param new_content [String] the new content the message should have. # @return [Message] the resulting message. def edit(new_content) response = API::Channel.edit_message(@bot.token, @channel.id, @id, new_content) Message.new(JSON.parse(response), @bot) end # Deletes this message. def delete API::Channel.delete_message(@bot.token, @channel.id, @id) nil end # Pins this message def pin API::Channel.pin_message(@bot.token, @channel.id, @id) @pinned = true nil end # Unpins this message def unpin API::Channel.unpin_message(@bot.token, @channel.id, @id) @pinned = false nil end # Add an {Await} for a message with the same user and channel. # @see Bot#add_await def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { from: @author.id, in: @channel.id }.merge(attributes), &block) end # @return [true, false] whether this message was sent by the current {Bot}. def from_bot? @author && @author.current_bot? end # @return [true, false] whether this message has been sent over a webhook. def webhook? !@webhook_id.nil? end # @!visibility private # @return [Array<String>] the emoji mentions found in the message def scan_for_emoji emoji = @content.split emoji = emoji.grep(/<:(?<name>\w+):(?<id>\d+)>?/) emoji end # @return [Array<Emoji>] the emotes that were used/mentioned in this message (Only returns Emoji the bot has access to, else nil). def emoji return if @content.nil? emoji = scan_for_emoji emoji.each do |element| @emoji << @bot.parse_mention(element) end @emoji end # Check if any emoji got used in this message # @return [true, false] whether or not any emoji got used def emoji? emoji = scan_for_emoji return true unless emoji.empty? end # Check if any reactions got used in this message # @return [true, false] whether or not this message has reactions def reactions? @reactions.any? end # The inspect method is overwritten to give more useful output def inspect "<Message content=\"#{@content}\" id=#{@id} timestamp=#{@timestamp} author=#{@author} channel=#{@channel}>" end end # A reaction to a message class Reaction # @return [Integer] the amount of users who have reacted with this reaction attr_reader :count # TODO: I have no idea what this is. # @return [true, false] me attr_reader :me # @return [Integer] the ID of the emoji, if it was custom attr_reader :id # @return [String] the name or unicode representation of the emoji attr_reader :name def initialize(data) @count = data['count'] @me = data['me'] @id = data['emoji']['id'] @name = data['emoji']['name'] end end # Server emoji class Emoji include IDObject # @return [String] the emoji name attr_reader :name # @return [Server] the server of this emoji attr_reader :server # @return [Array<Role>] roles this emoji is active for attr_reader :roles def initialize(data, bot, server) @bot = bot @roles = nil @name = data['name'] @server = server @id = data['id'].to_i process_roles(data['roles']) if server end # @return [String] the layout to mention it (or have it used) in a message def mention "<:#{@name}:#{@id}>" end alias_method :use, :mention alias_method :to_s, :mention # @return [String] the icon URL of the emoji def icon_url API.emoji_icon_url(@id) end # The inspect method is overwritten to give more useful output def inspect "<Emoji name=#{@name} id=#{@id}>" end # @!visibility private def process_roles(roles) @roles = [] return unless roles roles.each do |role_id| role = server.role(role_id) @roles << role end end end # Emoji that is not tailored to a server class GlobalEmoji include IDObject # @return [String] the emoji name attr_reader :name # @return [Hash<Integer => Array<Role>>] roles this emoji is active for in every server attr_reader :role_associations def initialize(data, bot) @bot = bot @roles = nil @name = data.name @id = data.id @role_associations = Hash.new([]) @role_associations[data.server.id] = data.roles end # @return [String] the layout to mention it (or have it used) in a message def mention "<:#{@name}:#{@id}>" end alias_method :use, :mention alias_method :to_s, :mention # @return [String] the icon URL of the emoji def icon_url API.emoji_icon_url(@id) end # The inspect method is overwritten to give more useful output def inspect "<GlobalEmoji name=#{@name} id=#{@id}>" end # @!visibility private def process_roles(roles) new_roles = [] return unless roles roles.each do role = server.role(role_id) new_roles << role end new_roles end end # Basic attributes a server should have module ServerAttributes # @return [String] this server's name. attr_reader :name # @return [String] the hexadecimal ID used to identify this server's icon. attr_reader :icon_id # Utility function to get the URL for the icon image # @return [String] the URL to the icon image def icon_url return nil unless @icon_id API.icon_url(@id, @icon_id) end end # Integration Account class IntegrationAccount # @return [String] this account's name. attr_reader :name # @return [Integer] this account's ID. attr_reader :id def initialize(data) @name = data['name'] @id = data['id'].to_i end end # Server integration class Integration include IDObject # @return [String] the integration name attr_reader :name # @return [Server] the server the integration is linked to attr_reader :server # @return [User] the user the integration is linked to attr_reader :user # @return [Role, nil] the role that this integration uses for "subscribers" attr_reader :role # @return [true, false] whether emoticons are enabled attr_reader :emoticon alias_method :emoticon?, :emoticon # @return [String] the integration type (Youtube, Twitch, etc.) attr_reader :type # @return [true, false] whether the integration is enabled attr_reader :enabled # @return [true, false] whether the integration is syncing attr_reader :syncing # @return [IntegrationAccount] the integration account information attr_reader :account # @return [Time] the time the integration was synced at attr_reader :synced_at # @return [Symbol] the behaviour of expiring subscribers (:remove = Remove User from role; :kick = Kick User from server) attr_reader :expire_behaviour alias_method :expire_behavior, :expire_behaviour # @return [Integer] the grace period before subscribers expire (in days) attr_reader :expire_grace_period def initialize(data, bot, server) @bot = bot @name = data['name'] @server = server @id = data['id'].to_i @enabled = data['enabled'] @syncing = data['syncing'] @type = data['type'] @account = IntegrationAccount.new(data['account']) @synced_at = Time.parse(data['synced_at']) @expire_behaviour = [:remove, :kick][data['expire_behavior']] @expire_grace_period = data['expire_grace_period'] @user = @bot.ensure_user(data['user']) @role = server.role(data['role_id']) || nil @emoticon = data['enable_emoticons'] end # The inspect method is overwritten to give more useful output def inspect "<Integration name=#{@name} id=#{@id} type=#{@type} enabled=#{@enabled}>" end end # A server on Discord class Server include IDObject include ServerAttributes # @return [String] the region the server is on (e. g. `amsterdam`). attr_reader :region # @return [Member] The server owner. attr_reader :owner # @return [Array<Channel>] an array of all the channels (text and voice) on this server. attr_reader :channels # @return [Array<Role>] an array of all the roles created on this server. attr_reader :roles # @return [Array<Emoji>] an array of all the emoji available on this server. attr_reader :emoji alias_method :emojis, :emoji # @return [true, false] whether or not this server is large (members > 100). If it is, # it means the members list may be inaccurate for a couple seconds after starting up the bot. attr_reader :large alias_method :large?, :large # @return [Array<Symbol>] the features of the server (eg. "INVITE_SPLASH") attr_reader :features # @return [Integer] the absolute number of members on this server, offline or not. attr_reader :member_count # @return [Symbol] the verification level of the server (:none = none, :low = 'Must have a verified email on their Discord account', :medium = 'Has to be registered with Discord for at least 5 minutes', :high = 'Has to be a member of this server for at least 10 minutes'). attr_reader :verification_level # @return [Integer] the amount of time after which a voice user gets moved into the AFK channel, in seconds. attr_reader :afk_timeout # @return [Channel, nil] the AFK voice channel of this server, or nil if none is set attr_reader :afk_channel # @return [Hash<Integer => VoiceState>] the hash (user ID => voice state) of voice states of members on this server attr_reader :voice_states # @!visibility private def initialize(data, bot, exists = true) @bot = bot @owner_id = data['owner_id'].to_i @id = data['id'].to_i update_data(data) @large = data['large'] @member_count = data['member_count'] @verification_level = [:none, :low, :medium, :high][data['verification_level']] @splash_id = nil @embed = nil @features = data['features'].map { |element| element.downcase.to_sym } @members = {} @voice_states = {} @emoji = {} process_roles(data['roles']) process_emoji(data['emojis']) process_members(data['members']) process_presences(data['presences']) process_channels(data['channels']) process_voice_states(data['voice_states']) # Whether this server's members have been chunked (resolved using op 8 and GUILD_MEMBERS_CHUNK) yet @chunked = false @processed_chunk_members = 0 # Only get the owner of the server actually exists (i. e. not for ServerDeleteEvent) @owner = member(@owner_id) if exists end # @return [Channel] The default channel on this server (usually called #general) def default_channel @bot.channel(@id) end alias_method :general_channel, :default_channel # Gets a role on this server based on its ID. # @param id [Integer] The role ID to look for. def role(id) @roles.find { |e| e.id == id } end # Gets a member on this server based on user ID # @param id [Integer] The user ID to look for # @param request [true, false] Whether the member should be requested from Discord if it's not cached def member(id, request = true) id = id.resolve_id return @members[id] if member_cached?(id) return nil unless request member = @bot.member(self, id) @members[id] = member rescue nil end # @return [Array<Member>] an array of all the members on this server. def members return @members.values if @chunked @bot.debug("Members for server #{@id} not chunked yet - initiating") @bot.request_chunks(@id) sleep 0.05 until @chunked @members.values end alias_method :users, :members # @return [Array<Integration>] an array of all the integrations connected to this server. def integrations integration = JSON.parse(API.server_integrations(@bot.token, @id)) integration.map { |element| Integration.new(element, @bot, self) } end # Cache @embed # @note For internal use only # @!visibility private def cache_embed @embed = JSON.parse(API.server(@bot.token, @id))['embed_enabled'] if @embed.nil? end # @return [true, false] whether or not the server has widget enabled def embed? cache_embed if @embed.nil? @embed end # @param include_idle [true, false] Whether to count idle members as online. # @param include_bots [true, false] Whether to include bot accounts in the count. # @return [Array<Member>] an array of online members on this server. def online_members(include_idle: false, include_bots: true) @members.values.select do |e| ((include_idle ? e.idle? : false) || e.online?) && (include_bots ? true : !e.bot_account?) end end alias_method :online_users, :online_members # @return [Array<Channel>] an array of text channels on this server def text_channels @channels.select(&:text?) end # @return [Array<Channel>] an array of voice channels on this server def voice_channels @channels.select(&:voice?) end # @return [String, nil] the widget URL to the server that displays the amount of online members in a # stylish way. `nil` if the widget is not enabled. def widget_url cache_embed if @embed.nil? return nil unless @embed API.widget_url(@id) end # @param style [Symbol] The style the picture should have. Possible styles are: # * `:banner1` creates a rectangular image with the server name, member count and icon, a "Powered by Discord" message on the bottom and an arrow on the right. # * `:banner2` creates a less tall rectangular image that has the same information as `banner1`, but the Discord logo on the right - together with the arrow and separated by a diagonal separator. # * `:banner3` creates an image similar in size to `banner1`, but it has the arrow in the bottom part, next to the Discord logo and with a "Chat now" text. # * `:banner4` creates a tall, almost square, image that prominently features the Discord logo at the top and has a "Join my server" in a pill-style button on the bottom. The information about the server is in the same format as the other three `banner` styles. # * `:shield` creates a very small, long rectangle, of the style you'd find at the top of GitHub `README.md` files. It features a small version of the Discord logo at the left and the member count at the right. # @return [String, nil] the widget banner URL to the server that displays the amount of online members, # server icon and server name in a stylish way. `nil` if the widget is not enabled. def widget_banner_url(style) return nil unless @embed cache_embed if @embed.nil? API.widget_url(@id, style) end # @return [String] the hexadecimal ID used to identify this server's splash image for their VIP invite page. def splash_id @splash_id = JSON.parse(API.server(@bot.token, @id))['splash'] if @splash_id.nil? @splash_id end # @return [String, nil] the splash image URL for the server's VIP invite page. # `nil` if there is no splash image. def splash_url splash_id if @splash_id.nil? return nil unless @splash_id API.splash_url(@id, @splash_id) end # Adds a role to the role cache # @note For internal use only # @!visibility private def add_role(role) @roles << role end # Removes a role from the role cache # @note For internal use only # @!visibility private def delete_role(role_id) @roles.reject! { |r| r.id == role_id } @members.each do |_, member| new_roles = member.roles.reject { |r| r.id == role_id } member.update_roles(new_roles) end @channels.each do |channel| overwrites = channel.permission_overwrites.reject { |id, _| id == role_id } channel.update_overwrites(overwrites) end end # Adds a member to the member cache. # @note For internal use only # @!visibility private def add_member(member) @members[member.id] = member @member_count += 1 end # Removes a member from the member cache. # @note For internal use only # @!visibility private def delete_member(user_id) @members.delete(user_id) @member_count -= 1 end # Checks whether a member is cached # @note For internal use only # @!visibility private def member_cached?(user_id) @members.include?(user_id) end # Adds a member to the cache # @note For internal use only # @!visibility private def cache_member(member) @members[member.id] = member end # Updates a member's voice state # @note For internal use only # @!visibility private def update_voice_state(data) user_id = data['user_id'].to_i if data['channel_id'] unless @voice_states[user_id] # Create a new voice state for the user @voice_states[user_id] = VoiceState.new(user_id) end # Update the existing voice state (or the one we just created) channel = @channels_by_id[data['channel_id'].to_i] @voice_states[user_id].update( channel, data['mute'], data['deaf'], data['self_mute'], data['self_deaf'] ) else # The user is not in a voice channel anymore, so delete its voice state @voice_states.delete(user_id) end end # Creates a channel on this server with the given name. # @param name [String] Name of the channel to create # @param type [Integer] Type of channel to create (0: text, 2: voice) # @return [Channel] the created channel. # @raise [ArgumentError] if type is not 0 or 2 def create_channel(name, type = 0) raise ArgumentError, 'Channel type must be either 0 (text) or 2 (voice)!' unless [0, 2].include?(type) response = API::Server.create_channel(@bot.token, @id, name, type) Channel.new(JSON.parse(response), @bot) end # Creates a role on this server which can then be modified. It will be initialized (on Discord's side) # with the regular role defaults the client uses, i. e. name is "new role", permissions are the default, # colour is the default etc. # @return [Role] the created role. def create_role response = API::Server.create_role(@bot.token, @id) role = Role.new(JSON.parse(response), @bot, self) @roles << role role end # @return [Array<User>] a list of banned users on this server. def bans users = JSON.parse(API::Server.bans(@bot.token, @id)) users.map { |e| User.new(e['user'], @bot) } end # Bans a user from this server. # @param user [User, #resolve_id] The user to ban. # @param message_days [Integer] How many days worth of messages sent by the user should be deleted. def ban(user, message_days = 0) API::Server.ban_user(@bot.token, @id, user.resolve_id, message_days) end # Unbans a previously banned user from this server. # @param user [User, #resolve_id] The user to unban. def unban(user) API::Server.unban_user(@bot.token, @id, user.resolve_id) end # Kicks a user from this server. # @param user [User, #resolve_id] The user to kick. def kick(user) API::Server.remove_member(@bot.token, @id, user.resolve_id) end # Forcibly moves a user into a different voice channel. Only works if the bot has the permission needed. # @param user [User] The user to move. # @param channel [Channel] The voice channel to move into. def move(user, channel) API::Server.update_member(@bot.token, @id, user.id, channel_id: channel.id) end # Deletes this server. Be aware that this is permanent and impossible to undo, so be careful! def delete API::Server.delete(@bot.token, @id) end # Leave the server def leave API::User.leave_server(@bot.token, @id) end # Transfers server ownership to another user. # @param user [User] The user who should become the new owner. def owner=(user) API::Server.transfer_ownership(@bot.token, @id, user.id) end # Sets the server's name. # @param name [String] The new server name. def name=(name) update_server_data(name: name) end # Moves the server to another region. This will cause a voice interruption of at most a second. # @param region [String] The new region the server should be in. def region=(region) update_server_data(region: region.to_s) end # Sets the server's icon. # @param icon [String, #read] The new icon, in base64-encoded JPG format. def icon=(icon) if icon.respond_to? :read icon_string = 'data:image/jpg;base64,' icon_string += Base64.strict_encode64(icon.read) update_server_data(icon: icon_string) else update_server_data(icon: icon) end end # Sets the server's AFK channel. # @param afk_channel [Channel, nil] The new AFK channel, or `nil` if there should be none set. def afk_channel=(afk_channel) update_server_data(afk_channel_id: afk_channel.resolve_id) end # Sets the amount of time after which a user gets moved into the AFK channel. # @param afk_timeout [Integer] The AFK timeout, in seconds. def afk_timeout=(afk_timeout) update_server_data(afk_timeout: afk_timeout) end # @return [true, false] whether this server has any emoji or not. def any_emoji? @emoji.any? end alias_method :has_emoji?, :any_emoji? alias_method :emoji?, :any_emoji? # Processes a GUILD_MEMBERS_CHUNK packet, specifically the members field # @note For internal use only # @!visibility private def process_chunk(members) process_members(members) @processed_chunk_members += members.length LOGGER.debug("Processed one chunk on server #{@id} - length #{members.length}") # Don't bother with the rest of the method if it's not truly the last packet return unless @processed_chunk_members == @member_count LOGGER.debug("Finished chunking server #{@id}") # Reset everything to normal @chunked = true @processed_chunk_members = 0 end # Updates the cached data with new data # @note For internal use only # @!visibility private def update_data(new_data) @name = new_data[:name] || new_data['name'] || @name @region = new_data[:region] || new_data['region'] || @region @icon_id = new_data[:icon] || new_data['icon'] || @icon_id @afk_timeout = new_data[:afk_timeout] || new_data['afk_timeout'].to_i || @afk_timeout @afk_channel_id = new_data[:afk_channel_id] || new_data['afk_channel_id'].to_i || @afk_channel.id begin @afk_channel = @bot.channel(@afk_channel_id, self) if @afk_channel_id.nonzero? && (!@afk_channel || @afk_channel_id != @afk_channel.id) rescue Discordrb::Errors::NoPermission LOGGER.debug("AFK channel #{@afk_channel_id} on server #{@id} is unreachable, setting to nil even though one exists") @afk_channel = nil end end # The inspect method is overwritten to give more useful output def inspect "<Server name=#{@name} id=#{@id} large=#{@large} region=#{@region} owner=#{@owner} afk_channel_id=#{@afk_channel_id} afk_timeout=#{@afk_timeout}>" end private def update_server_data(new_data) API::Server.update(@bot.token, @id, new_data[:name] || @name, new_data[:region] || @region, new_data[:icon_id] || @icon_id, new_data[:afk_channel_id] || @afk_channel_id, new_data[:afk_timeout] || @afk_timeout) update_data(new_data) end def process_roles(roles) # Create roles @roles = [] @roles_by_id = {} return unless roles roles.each do |element| role = Role.new(element, @bot, self) @roles << role @roles_by_id[role.id] = role end end def process_emoji(emoji) return if emoji.empty? emoji.each do |element| new_emoji = Emoji.new(element, @bot, self) @emoji[new_emoji.id] = new_emoji end end def process_members(members) return unless members members.each do |element| member = Member.new(element, self, @bot) @members[member.id] = member end end def process_presences(presences) # Update user statuses with presence info return unless presences presences.each do |element| next unless element['user'] user_id = element['user']['id'].to_i user = @members[user_id] if user user.status = element['status'].to_sym user.game = element['game'] ? element['game']['name'] : nil else LOGGER.warn "Rogue presence update! #{element['user']['id']} on #{@id}" end end end def process_channels(channels) @channels = [] @channels_by_id = {} return unless channels channels.each do |element| channel = @bot.ensure_channel(element, self) @channels << channel @channels_by_id[channel.id] = channel end end def process_voice_states(voice_states) return unless voice_states voice_states.each do |element| update_voice_state(element) end end end # A colour (red, green and blue values). Used for role colours. If you prefer the American spelling, the alias # {ColorRGB} is also available. class ColourRGB # @return [Integer] the red part of this colour (0-255). attr_reader :red # @return [Integer] the green part of this colour (0-255). attr_reader :green # @return [Integer] the blue part of this colour (0-255). attr_reader :blue # @return [Integer] the colour's RGB values combined into one integer. attr_reader :combined # Make a new colour from the combined value. # @param combined [Integer] The colour's RGB values combined into one integer def initialize(combined) @combined = combined @red = (combined >> 16) & 0xFF @green = (combined >> 8) & 0xFF @blue = combined & 0xFF end end # Alias for the class {ColourRGB} ColorRGB = ColourRGB end
# frozen_string_literal: true # These classes hold relevant Discord data, such as messages or channels. require 'ostruct' require 'discordrb/permissions' require 'discordrb/api' require 'discordrb/events/message' require 'time' require 'base64' # Discordrb module module Discordrb # The unix timestamp Discord IDs are based on DISCORD_EPOCH = 1_420_070_400_000 # Compares two objects based on IDs - either the objects' IDs are equal, or one object is equal to the other's ID. def self.id_compare(one_id, other) other.respond_to?(:resolve_id) ? (one_id.resolve_id == other.resolve_id) : (one_id == other) end # The maximum length a Discord message can have CHARACTER_LIMIT = 2000 # Splits a message into chunks of 2000 characters. Attempts to split by lines if possible. # @param msg [String] The message to split. # @return [Array<String>] the message split into chunks def self.split_message(msg) # If the messages is empty, return an empty array return [] if msg.empty? # Split the message into lines lines = msg.lines # Turn the message into a "triangle" of consecutively longer slices, for example the array [1,2,3,4] would become # [ # [1], # [1, 2], # [1, 2, 3], # [1, 2, 3, 4] # ] tri = [*0..(lines.length - 1)].map { |i| lines.combination(i + 1).first } # Join the individual elements together to get an array of strings with consecutively more lines joined = tri.map { |e| e.join("\n") } # Find the largest element that is still below the character limit, or if none such element exists return the first ideal = joined.max_by { |e| e.length > CHARACTER_LIMIT ? -1 : e.length } # If it's still larger than the character limit (none was smaller than it) split it into slices with the length # being the character limit, otherwise just return an array with one element ideal_ary = (ideal.length > CHARACTER_LIMIT) ? ideal.chars.each_slice(CHARACTER_LIMIT).map(&:join) : [ideal] # Slice off the ideal part and strip newlines rest = msg[ideal.length..-1].strip # If none remains, return an empty array -> we're done return [] unless rest # Otherwise, call the method recursively to split the rest of the string and add it onto the ideal array ideal_ary + split_message(rest) end # Mixin for objects that have IDs module IDObject # @return [Integer] the ID which uniquely identifies this object across Discord. attr_reader :id alias_method :resolve_id, :id # ID based comparison def ==(other) Discordrb.id_compare(@id, other) end # Estimates the time this object was generated on based on the beginning of the ID. This is fairly accurate but # shouldn't be relied on as Discord might change its algorithm at any time # @return [Time] when this object was created at def creation_time # Milliseconds ms = (@id >> 22) + DISCORD_EPOCH Time.at(ms / 1000.0) end end # Mixin for the attributes users should have module UserAttributes # @return [String] this user's username attr_reader :username alias_method :name, :username # @return [String] this user's discriminator which is used internally to identify users with identical usernames. attr_reader :discriminator alias_method :discrim, :discriminator alias_method :tag, :discriminator alias_method :discord_tag, :discriminator # @return [true, false] whether this user is a Discord bot account attr_reader :bot_account alias_method :bot_account?, :bot_account # @return [String] the ID of this user's current avatar, can be used to generate an avatar URL. # @see #avatar_url attr_reader :avatar_id # Utility function to mention users in messages # @return [String] the mention code in the form of <@id> def mention "<@#{@id}>" end # Utility function to get Discord's distinct representation of a user, i. e. username + discriminator # @return [String] distinct representation of user def distinct "#{@username}##{@discriminator}" end # Utility function to get a user's avatar URL. # @return [String] the URL to the avatar image. def avatar_url API.avatar_url(@id, @avatar_id) end end # User on Discord, including internal data like discriminators class User include IDObject include UserAttributes # @!attribute [r] status # @return [Symbol] the current online status of the user (`:online`, `:offline` or `:idle`) attr_accessor :status # @!attribute [r] game # @return [String, nil] the game the user is currently playing, or `nil` if none is being played. attr_accessor :game def initialize(data, bot) @bot = bot @username = data['username'] @id = data['id'].to_i @discriminator = data['discriminator'] @avatar_id = data['avatar'] @roles = {} @bot_account = false @bot_account = true if data['bot'] @status = :offline end # Get a user's PM channel or send them a PM # @overload pm # Creates a private message channel for this user or returns an existing one if it already exists # @return [Channel] the PM channel to this user. # @overload pm(content) # Sends a private to this user. # @param content [String] The content to send. # @return [Message] the message sent to this user. def pm(content = nil) if content # Recursively call pm to get the channel, then send a message to it channel = pm channel.send_message(content) else # If no message was specified, return the PM channel @bot.private_channel(@id) end end # Set the user's name # @note for internal use only # @!visibility private def update_username(username) @username = username end # Add an await for a message from this user. Specifically, this adds a global await for a MessageEvent with this # user's ID as a :from attribute. # @see Bot#add_await def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { from: @id }.merge(attributes), &block) end # Gets the member this user is on a server # @param server [Server] The server to get the member for # @return [Member] this user as a member on a particular server def on(server) id = server.resolve_id @bot.server(id).member(@id) end # Is the user the bot? # @return [true, false] whether this user is the bot def current_bot? @bot.bot_user.id == @id end # The inspect method is overwritten to give more useful output def inspect "<User username=#{@username} id=#{@id} discriminator=#{@discriminator}>" end end # Mixin for the attributes members and private members should have module MemberAttributes # @return [true, false] whether this member is muted server-wide. attr_reader :mute alias_method :muted?, :mute # @return [true, false] whether this member is deafened server-wide. attr_reader :deaf alias_method :deafened?, :deaf # @return [Time] when this member joined the server. attr_reader :joined_at # @return [Array<Role>] the roles this member has. attr_reader :roles # @return [Server] the server this member is on. attr_reader :server # @return [Channel] the voice channel the user is in. attr_reader :voice_channel end # Mixin to calculate resulting permissions from overrides etc. module PermissionCalculator # Checks whether this user can do the particular action, regardless of whether it has the permission defined, # through for example being the server owner or having the Manage Roles permission # @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list. # @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked. # @return [true, false] whether or not this user has the permission. def permission?(action, channel = nil) # If the member is the server owner, it irrevocably has all permissions. return true if owner? # First, check whether the user has Manage Roles defined. # (Coincidentally, Manage Permissions is the same permission as Manage Roles, and a # Manage Permissions deny overwrite will override Manage Roles, so we can just check for # Manage Roles once and call it a day.) return true if defined_permission?(:manage_roles, channel) # Otherwise, defer to defined_permission defined_permission?(action, channel) end # Checks whether this user has a particular permission defined (i. e. not implicit, through for example # Manage Roles) # @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list. # @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked. # @return [true, false] whether or not this user has the permission defined. def defined_permission?(action, channel = nil) # Get the permission the user's roles have role_permission = defined_role_permission?(action, channel) # Once we have checked the role permission, we have to check the channel overrides for the # specific user user_specific_override = permission_overwrite(action, channel, id) # Use the ID reader as members have no ID instance variable # Merge the two permissions - if an override is defined, it has to be allow, otherwise we only care about the role return role_permission unless user_specific_override user_specific_override == :allow end # Define methods for querying permissions Discordrb::Permissions::Flags.each_value do |flag| define_method "can_#{flag}?" do |channel = nil| permission? flag, channel end end private def defined_role_permission?(action, channel) # For each role, check if # (1) the channel explicitly allows or permits an action for the role and # (2) if the user is allowed to do the action if the channel doesn't specify @roles.reduce(false) do |can_act, role| # Get the override defined for the role on the channel channel_allow = permission_overwrite(action, channel, role.id) can_act = if channel_allow # If the channel has an override, check whether it is an allow - if yes, # the user can act, if not, it can't channel_allow == :allow else # Otherwise defer to the role role.permissions.instance_variable_get("@#{action}") || can_act end can_act end end def permission_overwrite(action, channel, id) # If no overwrites are defined, or no channel is set, no overwrite will be present return nil unless channel && channel.permission_overwrites[id] # Otherwise, check the allow and deny objects allow = channel.permission_overwrites[id].allow deny = channel.permission_overwrites[id].deny if allow.instance_variable_get("@#{action}") :allow elsif deny.instance_variable_get("@#{action}") :deny end # If there's no variable defined, nil will implicitly be returned end end # A member is a user on a server. It differs from regular users in that it has roles, voice statuses and things like # that. class Member < DelegateClass(User) include MemberAttributes # @!visibility private def initialize(data, server, bot) @bot = bot @user = bot.ensure_user(data['user']) super @user # Initialize the delegate class # Somehow, Discord doesn't send the server ID in the standard member format... raise ArgumentError, 'Cannot create a member without any information about the server!' if server.nil? && data['guild_id'].nil? @server = server || bot.server(data['guild_id'].to_i) # Initialize the roles by getting the roles from the server one-by-one update_roles(data['roles']) @deaf = data['deaf'] @mute = data['mute'] @joined_at = data['joined_at'] ? Time.parse(data['joined_at']) : nil end # @return [true, false] whether this member is the server owner. def owner? @server.owner == self end # Update this member's roles # @note For internal use only. # @!visibility private def update_roles(roles) @roles = roles.map do |role_id| @server.role(role_id.to_i) end end # Update this member's voice state # @note For internal use only. # @!visibility private def update_voice_state(channel, mute, deaf, self_mute, self_deaf) @voice_channel = channel @mute = mute @deaf = deaf @self_mute = self_mute @self_deaf = self_deaf end include PermissionCalculator # Overwriting inspect for debug purposes def inspect "<Member user=#{@user.inspect} server=#{@server.inspect} joined_at=#{@joined_at} roles=#{@roles.inspect} voice_channel=#{@voice_channel.inspect} mute=#{@mute} deaf=#{@deaf} self_mute=#{@self_mute} self_deaf=#{@self_deaf}>" end end # Recipients are members on private channels - they exist for completeness purposes, but all # the attributes will be empty. class Recipient < DelegateClass(User) include MemberAttributes # @return [Channel] the private channel this recipient is the recipient of. attr_reader :channel # @!visibility private def initialize(user, channel, bot) @bot = bot @channel = channel raise ArgumentError, 'Tried to create a recipient for a public channel!' unless @channel.private? @user = user super @user # Member attributes @mute = @deaf = @self_mute = @self_deaf = false @voice_channel = nil @server = nil @roles = [] @joined_at = @channel.creation_time end # Overwriting inspect for debug purposes def inspect "<Recipient user=#{@user.inspect} channel=#{@channel.inspect}>" end end # This class is a special variant of User that represents the bot's user profile (things like email addresses and the avatar). # It can be accessed using {Bot#profile}. class Profile < User def initialize(data, bot, email, password) super(data, bot) @email = email @password = password end # Whether or not the user is the bot. The Profile can only ever be the bot user, so this always returns true. # @return [true] def current_bot? true end # Sets the bot's username. # @param username [String] The new username. def username=(username) update_profile_data(username: username) end # Sets the bot's email address. If you use this method, make sure that the login email in the script matches this # one afterwards, so the bot doesn't have any trouble logging in in the future. # @param email [String] The new email address. def email=(email) update_profile_data(email: email) end # Changes the bot's password. This will invalidate all tokens so you will have to relog the bot. # @param password [String] The new password. def password=(password) update_profile_data(new_password: password) end # Changes the bot's avatar. # @param avatar [String, #read] A JPG file to be used as the avatar, either # something readable (e. g. File) or as a data URL. def avatar=(avatar) if avatar.respond_to? :read avatar_string = 'data:image/jpg;base64,' avatar_string += Base64.strict_encode64(avatar.read) update_profile_data(avatar: avatar_string) else update_profile_data(avatar: avatar) end end # Updates the cached profile data with the new one. # @note For internal use only. # @!visibility private def update_data(new_data) @email = new_data[:email] || @email @password = new_data[:new_password] || @password @username = new_data[:username] || @username @avatar_id = new_data[:avatar_id] || @avatar_id end # The inspect method is overwritten to give more useful output def inspect "<Profile email=#{@email} user=#{super}>" end private def update_profile_data(new_data) API.update_user(@bot.token, new_data[:email] || @email, @password, new_data[:username] || @username, new_data[:avatar], new_data[:new_password] || nil) update_data(new_data) end end # A Discord role that contains permissions and applies to certain users class Role include IDObject # @return [Permissions] this role's permissions. attr_reader :permissions # @return [String] this role's name ("new role" if it hasn't been changed) attr_reader :name # @return [true, false] whether or not this role should be displayed separately from other users attr_reader :hoist # @return [ColourRGB] the role colour attr_reader :colour alias_method :color, :colour # This class is used internally as a wrapper to a Role object that allows easy writing of permission data. class RoleWriter # @!visibility private def initialize(role, token) @role = role @token = token end # Write the specified permission data to the role, without updating the permission cache # @param bits [Integer] The packed permissions to write. def write(bits) @role.send(:packed=, bits, false) end end # @!visibility private def initialize(data, bot, server = nil) @bot = bot @server = server @permissions = Permissions.new(data['permissions'], RoleWriter.new(self, @bot.token)) @name = data['name'] @id = data['id'].to_i @hoist = data['hoist'] @colour = ColourRGB.new(data['color']) end # Updates the data cache from another Role object # @note For internal use only # @!visibility private def update_from(other) @permissions = other.permissions @name = other.name @hoist = other.hoist @colour = other.colour end # Updates the data cache from a hash containing data # @note For internal use only # @!visibility private def update_data(new_data) @name = new_data[:name] || new_data['name'] || @name @hoist = new_data['hoist'] unless new_data['hoist'].nil? @hoist = new_data[:hoist] unless new_data[:hoist].nil? @colour = new_data[:colour] || (new_data['color'] ? ColourRGB.new(new_data['color']) : @colour) end # Sets the role name to something new # @param name [String] The name that should be set def name=(name) update_role_data(name: name) end # Changes whether or not this role is displayed at the top of the user list # @param hoist [true, false] The value it should be changed to def hoist=(hoist) update_role_data(hoist: hoist) end # Sets the role colour to something new # @param colour [ColourRGB] The new colour def colour=(colour) update_role_data(colour: colour) end alias_method :color=, :colour= # Changes the internal packed permissions # @note For internal use only # @!visibility private def packed=(packed, update_perms = true) update_role_data(permissions: packed) @permissions.bits = packed if update_perms end # Delets this role. This cannot be undone without recreating the role! def delete API.delete_role(@bot.token, @server.id, @id) @server.delete_role(@id) end # The inspect method is overwritten to give more useful output def inspect "<Role name=#{@name} permissions=#{@permissions.inspect} hoist=#{@hoist} colour=#{@colour.inspect} server=#{@server.inspect}>" end private def update_role_data(new_data) API.update_role(@bot.token, @server.id, @id, new_data[:name] || @name, (new_data[:colour] || @colour).combined, new_data[:hoist].nil? ? false : !@hoist.nil?, new_data[:permissions] || @permissions.bits) update_data(new_data) end end # A Discord invite to a channel class Invite # @return [Channel] the channel this invite references. attr_reader :channel # @return [Server] the server this invite references. attr_reader :server # @return [Integer] the amount of uses left on this invite. attr_reader :uses # @return [User, nil] the user that made this invite. May also be nil if the user can't be determined. attr_reader :inviter # @return [true, false] whether or not this invite is temporary. attr_reader :temporary # @return [true, false] whether this invite is still valid. attr_reader :revoked # @return [true, false] whether this invite is in xkcd format (i. e. "Human readable" in the invite settings) attr_reader :xkcd # @return [String] this invite's code attr_reader :code alias_method :max_uses, :uses alias_method :user, :inviter alias_method :temporary?, :temporary alias_method :revoked?, :revoked alias_method :xkcd?, :xkcd # @!visibility private def initialize(data, bot) @bot = bot @channel = Channel.new(data['channel'], bot) @server = Server.new(data['guild'], bot) @uses = data['uses'] @inviter = data['inviter'] ? (@bot.user(data['inviter']['id'].to_i) || User.new(data['inviter'], bot)) : nil @temporary = data['temporary'] @revoked = data['revoked'] @xkcd = data['xkcdpass'] @code = data['code'] end # Code based comparison def ==(other) other.respond_to?(:code) ? (@code == other.code) : (@code == other) end # Deletes this invite def delete API.delete_invite(@bot.token, @code) end alias_method :revoke, :delete # The inspect method is overwritten to give more useful output def inspect "<Invite code=#{@code} channel=#{@channel} uses=#{@uses} temporary=#{@temporary} revoked=#{@revoked} xkcd=#{@xkcd}>" end end # A Discord channel, including data like the topic class Channel # The type string that stands for a text channel # @see Channel#type TEXT_TYPE = 'text'.freeze # The type string that stands for a voice channel # @see Channel#type VOICE_TYPE = 'voice'.freeze include IDObject # @return [String] this channel's name. attr_reader :name # @return [Server, nil] the server this channel is on. If this channel is a PM channel, it will be nil. attr_reader :server # @return [String] the type of this channel (currently either 'text' or 'voice') attr_reader :type # @return [Recipient, nil] the recipient of the private messages, or nil if this is not a PM channel attr_reader :recipient # @return [String] the channel's topic attr_reader :topic # @return [Integer] the channel's position on the channel list attr_reader :position # This channel's permission overwrites, represented as a hash of role/user ID to an OpenStruct which has the # `allow` and `deny` properties which are {Permissions} objects respectively. # @return [Hash<Integer => OpenStruct>] the channel's permission overwrites attr_reader :permission_overwrites # @return [true, false] whether or not this channel is a PM channel. def private? @server.nil? end # @return [String] a string that will mention the channel as a clickable link on Discord. def mention "<##{@id}>" end # @!visibility private def initialize(data, bot, server = nil) @bot = bot # data is a sometimes a Hash and othertimes an array of Hashes, you only want the last one if it's an array data = data[-1] if data.is_a?(Array) @id = data['id'].to_i @type = data['type'] || TEXT_TYPE @topic = data['topic'] @position = data['position'] @is_private = data['is_private'] if @is_private recipient_user = bot.ensure_user(data['recipient']) @recipient = Recipient.new(recipient_user, self, bot) @name = @recipient.username else @name = data['name'] @server = if server server else bot.server(data['guild_id'].to_i) end end # Populate permission overwrites @permission_overwrites = {} return unless data['permission_overwrites'] data['permission_overwrites'].each do |element| role_id = element['id'].to_i deny = Permissions.new(element['deny']) allow = Permissions.new(element['allow']) @permission_overwrites[role_id] = OpenStruct.new @permission_overwrites[role_id].deny = deny @permission_overwrites[role_id].allow = allow end end # @return [true, false] whether or not this channel is a text channel def text? @type == TEXT_TYPE end # @return [true, false] whether or not this channel is a voice channel def voice? @type == VOICE_TYPE end # Sends a message to this channel. # @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error. # @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech. # @return [Message] the message that was sent. def send_message(content, tts = false) @bot.send_message(@id, content, tts) end # Sends multiple messages to a channel # @param content [Array<String>] The messages to send. def send_multiple(content) content.each { |e| send_message(e) } end # Splits a message into chunks whose length is at most the Discord character limit, then sends them individually. # Useful for sending long messages, but be wary of rate limits! def split_send(content) send_multiple(Discordrb.split_message(content)) end # Sends a file to this channel. If it is an image, it will be embedded. # @param file [File] The file to send. There's no clear size limit for this, you'll have to attempt it for yourself (most non-image files are fine, large images may fail to embed) def send_file(file) @bot.send_file(@id, file) end # Permanently deletes this channel def delete API.delete_channel(@bot.token, @id) end # Sets this channel's name. The name must be alphanumeric with dashes, unless this is a voice channel (then there are no limitations) # @param name [String] The new name. def name=(name) @name = name update_channel_data end # Sets this channel's topic. # @param topic [String] The new topic. def topic=(topic) @topic = topic update_channel_data end # Sets this channel's position in the list. # @param position [Integer] The new position. def position=(position) @position = position update_channel_data end # Defines a permission overwrite for this channel that sets the specified thing to the specified allow and deny # permission sets, or change an existing one. # @param thing [User, Role] What to define an overwrite for. # @param allow [#bits, Permissions, Integer] The permission sets that should receive an `allow` override (i. e. a # green checkmark on Discord) # @param deny [#bits, Permissions, Integer] The permission sets that should receive a `deny` override (i. e. a red # cross on Discord) # @example Define a permission overwrite for a user that can then mention everyone and use TTS, but not create any invites # allow = Discordrb::Permissions.new # allow.can_mention_everyone = true # allow.can_send_tts_messages = true # # deny = Discordrb::Permissions.new # deny.can_create_instant_invite = true # # channel.define_overwrite(user, allow, deny) def define_overwrite(thing, allow, deny) allow_bits = allow.respond_to?(:bits) ? allow.bits : allow deny_bits = deny.respond_to?(:bits) ? deny.bits : deny if thing.is_a? User API.update_user_overrides(@bot.token, @id, thing.id, allow_bits, deny_bits) elsif thing.is_a? Role API.update_role_overrides(@bot.token, @id, thing.id, allow_bits, deny_bits) end end # Updates the cached data from another channel. # @note For internal use only # @!visibility private def update_from(other) @topic = other.topic @name = other.name @recipient = other.recipient @permission_overwrites = other.permission_overwrites end # The list of users currently in this channel. This is mostly useful for a voice channel, for a text channel it will # just return the users on the server that are online. # @return [Array<Member>] the users in this channel def users if @type == 'text' @server.members.select { |u| u.status != :offline } else @server.members.select do |user| user.voice_channel.id == @id if user.voice_channel end end end # Retrieves some of this channel's message history. # @param amount [Integer] How many messages to retrieve. This must be less than or equal to 100, if it is higher # than 100 it will be treated as 100 on Discord's side. # @param before_id [Integer] The ID of the most recent message the retrieval should start at, or nil if it should # start at the current message. # @param after_id [Integer] The ID of the oldest message the retrieval should start at, or nil if it should start # as soon as possible with the specified amount. # @return [Array<Message>] the retrieved messages. def history(amount, before_id = nil, after_id = nil) logs = API.channel_log(@bot.token, @id, amount, before_id, after_id) JSON.parse(logs).map { |message| Message.new(message, @bot) } end # Deletes the last N messages on this channel. # @note Each delete request is performed in a separate thread for performance reasons, so if a large number of # messages are pruned, many threads will be created. # @param amount [Integer] How many messages to delete. Must be 100 or less (Discord limitation) # @raise [ArgumentError] if more than 100 messages are requested. def prune(amount) raise ArgumentError, "Can't prune more than 100 messages!" if amount > 100 threads = [] history(amount).each do |message| threads << Thread.new { message.delete } end # Make sure all requests have finished threads.each(&:join) # Delete the threads threads.map! { nil } end # Updates the cached permission overwrites # @note For internal use only # @!visibility private def update_overwrites(overwrites) @permission_overwrites = overwrites end # Add an {Await} for a message in this channel. This is identical in functionality to adding a # {Discordrb::Events::MessageEvent} await with the `in` attribute as this channel. # @see Bot#add_await def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { in: @id }.merge(attributes), &block) end # Creates a new invite to this channel. # @param max_age [Integer] How many seconds this invite should last. # @param max_uses [Integer] How many times this invite should be able to be used. # @param temporary [true, false] Whether membership should be temporary (kicked after going offline). # @param xkcd [true, false] Whether or not the invite should be human-readable. # @return [Invite] the created invite. def make_invite(max_age = 0, max_uses = 0, temporary = false, xkcd = false) response = API.create_invite(@bot.token, @id, max_age, max_uses, temporary, xkcd) Invite.new(JSON.parse(response), @bot) end # Starts typing, which displays the typing indicator on the client for five seconds. # If you want to keep typing you'll have to resend this every five seconds. (An abstraction # for this will eventually be coming) def start_typing API.start_typing(@bot.token, @id) end alias_method :send, :send_message alias_method :message, :send_message alias_method :invite, :make_invite # The inspect method is overwritten to give more useful output def inspect "<Channel name=#{@name} id=#{@id} topic=\"#{@topic}\" type=#{@type} position=#{@position} server=#{@server}>" end private def update_channel_data API.update_channel(@bot.token, @id, @name, @topic, @position) end end # An attachment to a message class Attachment include IDObject # @return [Message] the message this attachment belongs to. attr_reader :message # @return [String] the CDN URL this attachment can be downloaded at. attr_reader :url # @return [String] the attachment's proxy URL - I'm not sure what exactly this does, but I think it has something to # do with CDNs attr_reader :proxy_url # @return [String] the attachment's filename. attr_reader :filename # @return [Integer] the attachment's file size in bytes. attr_reader :size # @return [Integer, nil] the width of an image file, in pixels, or nil if the file is not an image. attr_reader :width # @return [Integer, nil] the height of an image file, in pixels, or nil if the file is not an image. attr_reader :height # @!visibility private def initialize(data, message, bot) @bot = bot @message = message @url = data['url'] @proxy_url = data['proxy_url'] @filename = data['filename'] @size = data['size'] @width = data['width'] @height = data['height'] end # @return [true, false] whether this file is an image file. def image? !(@width.nil? || @height.nil?) end end # A message on Discord that was sent to a text channel class Message include IDObject # @return [String] the content of this message. attr_reader :content # @return [Member] the user that sent this message. attr_reader :author # @return [Channel] the channel in which this message was sent. attr_reader :channel # @return [Time] the timestamp at which this message was sent. attr_reader :timestamp # @return [Array<User>] the users that were mentioned in this message. attr_reader :mentions # @return [Array<Attachment>] the files attached to this message. attr_reader :attachments alias_method :user, :author alias_method :text, :content alias_method :to_s, :content # @!visibility private def initialize(data, bot) @bot = bot @content = data['content'] @channel = bot.channel(data['channel_id'].to_i) @author = if data['author'] if @channel.private? # Turn the message user into a recipient - we can't use the channel recipient # directly because the bot may also send messages to the channel Recipient.new(bot.user(data['author']['id'].to_i), @channel, bot) else @channel.server.member(data['author']['id'].to_i) end end @timestamp = Time.parse(data['timestamp']) @id = data['id'].to_i @mentions = [] data['mentions'].each do |element| @mentions << bot.ensure_user(element) end if data['mentions'] @attachments = data['attachments'].map { |e| Attachment.new(e, self, @bot) } end # Replies to this message with the specified content. # @see Channel#send_message def reply(content) @channel.send_message(content) end # Edits this message to have the specified content instead. # @param new_content [String] the new content the message should have. # @return [Message] the resulting message. def edit(new_content) response = API.edit_message(@bot.token, @channel.id, @id, new_content) Message.new(JSON.parse(response), @bot) end # Deletes this message. def delete API.delete_message(@bot.token, @channel.id, @id) nil end # Add an {Await} for a message with the same user and channel. # @see Bot#add_await def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { from: @author.id, in: @channel.id }.merge(attributes), &block) end # @return [true, false] whether this message was sent by the current {Bot}. def from_bot? @author.current_bot? end # The inspect method is overwritten to give more useful output def inspect "<Message content=\"#{@content}\" id=#{@id} timestamp=#{@timestamp} author=#{@author} channel=#{@channel}>" end end # Basic attributes a server should have module ServerAttributes # @return [String] this server's name. attr_reader :name # @return [String] the hexadecimal ID used to identify this server's icon. attr_reader :icon_id # Utility function to get the URL for the icon image # @return [String] the URL to the icon image def icon_url API.icon_url(@id, @icon_id) end end # A server on Discord class Server include IDObject include ServerAttributes # @return [String] the region the server is on (e. g. `amsterdam`). attr_reader :region # @return [Member] The server owner. attr_reader :owner # @return [Array<Channel>] an array of all the channels (text and voice) on this server. attr_reader :channels # @return [Array<Role>] an array of all the roles created on this server. attr_reader :roles # @return [true, false] whether or not this server is large (members > 100). If it is, # it means the members list may be inaccurate for a couple seconds after starting up the bot. attr_reader :large alias_method :large?, :large # @return [Integer] the absolute number of members on this server, offline or not. attr_reader :member_count # @return [Integer] the amount of time after which a voice user gets moved into the AFK channel, in seconds. attr_reader :afk_timeout # @return [Channel, nil] the AFK voice channel of this server, or nil if none is set attr_reader :afk_channel # @!visibility private def initialize(data, bot) @bot = bot @owner_id = data['owner_id'].to_i @id = data['id'].to_i update_data(data) @large = data['large'] @member_count = data['member_count'] @members = {} process_roles(data['roles']) process_members(data['members']) process_presences(data['presences']) process_channels(data['channels']) process_voice_states(data['voice_states']) # Whether this server's members have been chunked (resolved using op 8 and GUILD_MEMBERS_CHUNK) yet @chunked = false @processed_chunk_members = 0 @owner = member(@owner_id) end # @return [Channel] The default channel on this server (usually called #general) def default_channel @bot.channel(@id) end alias_method :general_channel, :default_channel # Gets a role on this server based on its ID. # @param id [Integer] The role ID to look for. def role(id) @roles.find { |e| e.id == id } end # Gets a member on this server based on user ID # @param id [Integer] The user ID to look for def member(id) id = id.resolve_id return @members[id] if member_cached?(id) member = bot.member(@id, id) @members[id] = member end # @return [Array<Member>] an array of all the members on this server. def members return @members.values if @chunked @bot.debug("Members for server #{@id} not chunked yet - initiating") @bot.request_chunks(@id) sleep 0.05 until @chunked @members.values end alias_method :users, :members # Adds a role to the role cache # @note For internal use only # @!visibility private def add_role(role) @roles << role end # Removes a role from the role cache # @note For internal use only # @!visibility private def delete_role(role_id) @roles.reject! { |r| r.id == role_id } @members.each do |_, member| new_roles = member.roles.reject { |r| r.id == role_id } member.update_roles(new_roles) end @channels.each do |channel| overwrites = channel.permission_overwrites.reject { |id, _| id == role_id } channel.update_overwrites(overwrites) end end # Adds a member to the member cache. # @note For internal use only # @!visibility private def add_member(member) @members[member.id] = member @member_count += 1 end # Removes a member from the member cache. # @note For internal use only # @!visibility private def delete_member(user_id) @members.delete(user_id) @member_count -= 1 end # Checks whether a member is cached # @note For internal use only # @!visibility private def member_cached?(user_id) @members.include?(user_id) end # Adds a member to the cache # @note For internal use only # @!visibility private def cache_member(member) @members[member.id] = member end # Creates a channel on this server with the given name. # @return [Channel] the created channel. def create_channel(name, type = 'text') response = API.create_channel(@bot.token, @id, name, type) Channel.new(JSON.parse(response), @bot) end # Creates a role on this server which can then be modified. It will be initialized (on Discord's side) # with the regular role defaults the client uses, i. e. name is "new role", permissions are the default, # colour is the default etc. # @return [Role] the created role. def create_role response = API.create_role(@bot.token, @id) role = Role.new(JSON.parse(response), @bot, self) @roles << role role end # @return [Array<User>] a list of banned users on this server. def bans users = JSON.parse(API.bans(@bot.token, @id)) users.map { |e| User.new(e['user'], @bot) } end # Bans a user from this server. # @param user [User] The user to ban. # @param message_days [Integer] How many days worth of messages sent by the user should be deleted. def ban(user, message_days = 0) API.ban_user(@bot.token, @id, user.id, message_days) end # Unbans a previously banned user from this server. # @param user [User] The user to unban. def unban(user) API.unban_user(@bot.token, @id, user.id) end # Kicks a user from this server. # @param user [User] The user to kick. def kick(user) API.kick_user(@bot.token, @id, user.id) end # Forcibly moves a user into a different voice channel. Only works if the bot has the permission needed. # @param user [User] The user to move. # @param channel [Channel] The voice channel to move into. def move(user, channel) API.move_user(@bot.token, @id, user.id, channel.id) end # Deletes this server. Be aware that this is permanent and impossible to undo, so be careful! def delete API.delete_server(@bot.token, @id) end # Leave the server def leave API.leave_server(@bot.token, @id) end # Transfers server ownership to another user. # @param user [User] The user who should become the new owner. def owner=(user) API.transfer_ownership(@bot.token, @id, user.id) end # Sets the server's name. # @param name [String] The new server name. def name=(name) update_server_data(name: name) end # Moves the server to another region. This will cause a voice interruption of at most a second. # @param region [String] The new region the server should be in. def region=(region) update_server_data(region: region.to_s) end # Sets the server's icon. # @param icon [String, #read] The new icon, in base64-encoded JPG format. def icon=(icon) if icon.respond_to? :read icon_string = 'data:image/jpg;base64,' icon_string += Base64.strict_encode64(icon.read) update_server_data(icon: icon_string) else update_server_data(icon: icon) end end # Sets the server's AFK channel. # @param afk_channel [Channel, nil] The new AFK channel, or `nil` if there should be none set. def afk_channel=(afk_channel) update_server_data(afk_channel_id: afk_channel.resolve_id) end # @deprecated Use #afk_channel= with the ID instead. def afk_channel_id=(afk_channel_id) update_server_data(afk_channel_id: afk_channel_id) end # Sets the amount of time after which a user gets moved into the AFK channel. # @param afk_timeout [Integer] The AFK timeout, in seconds. def afk_timeout=(afk_timeout) update_server_data(afk_timeout: afk_timeout) end # Processes a GUILD_MEMBERS_CHUNK packet, specifically the members field # @note For internal use only # @!visibility private def process_chunk(members) process_members(members) @processed_chunk_members += members.length LOGGER.debug("Processed one chunk on server #{@id} - length #{members.length}") # Don't bother with the rest of the method if it's not truly the last packet return unless @processed_chunk_members == @member_count LOGGER.debug("Finished chunking server #{@id}") # Reset everything to normal @chunked = true @processed_chunk_members = 0 end # Updates the cached data with new data # @note For internal use only # @!visibility private def update_data(new_data) @name = new_data[:name] || new_data['name'] || @name @region = new_data[:region] || new_data['region'] || @region @icon_id = new_data[:icon] || new_data['icon'] || @icon_id @afk_timeout = new_data[:afk_timeout] || new_data['afk_timeout'].to_i || @afk_timeout @afk_channel_id = new_data[:afk_channel_id] || new_data['afk_channel_id'].to_i || @afk_channel.id @afk_channel = @bot.channel(@afk_channel_id, self) if @afk_channel_id != 0 && (!@afk_channel || @afk_channel_id != @afk_channel.id) end # The inspect method is overwritten to give more useful output def inspect "<Server name=#{@name} id=#{@id} large=#{@large} region=#{@region} owner=#{@owner} afk_channel_id=#{@afk_channel_id} afk_timeout=#{@afk_timeout}>" end private def update_server_data(new_data) API.update_server(@bot.token, @id, new_data[:name] || @name, new_data[:region] || @region, new_data[:icon_id] || @icon_id, new_data[:afk_channel_id] || @afk_channel_id, new_data[:afk_timeout] || @afk_timeout) update_data(new_data) end def process_roles(roles) # Create roles @roles = [] @roles_by_id = {} return unless roles roles.each do |element| role = Role.new(element, @bot, self) @roles << role @roles_by_id[role.id] = role end end def process_members(members) return unless members members.each do |element| member = Member.new(element, self, @bot) @members[member.id] = member end end def process_presences(presences) # Update user statuses with presence info return unless presences presences.each do |element| next unless element['user'] user_id = element['user']['id'].to_i user = @members[user_id] if user user.status = element['status'].to_sym user.game = element['game'] ? element['game']['name'] : nil end end end def process_channels(channels) @channels = [] @channels_by_id = {} return unless channels channels.each do |element| channel = Channel.new(element, @bot, self) @channels << channel @channels_by_id[channel.id] = channel end end def process_voice_states(voice_states) return unless voice_states voice_states.each do |element| user_id = element['user_id'].to_i member = @members[user_id] next unless member channel_id = element['channel_id'].to_i channel = channel_id ? @channels_by_id[channel_id] : nil member.update_voice_state( channel, element['mute'], element['deaf'], element['self_mute'], element['self_deaf']) end end end # A colour (red, green and blue values). Used for role colours. If you prefer the American spelling, the alias # {ColorRGB} is also available. class ColourRGB # @return [Integer] the red part of this colour (0-255). attr_reader :red # @return [Integer] the green part of this colour (0-255). attr_reader :green # @return [Integer] the blue part of this colour (0-255). attr_reader :blue # @return [Integer] the colour's RGB values combined into one integer. attr_reader :combined # Make a new colour from the combined value. # @param combined [Integer] The colour's RGB values combined into one integer def initialize(combined) @combined = combined @red = (combined >> 16) & 0xFF @green = (combined >> 8) & 0xFF @blue = combined & 0xFF end end # Alias for the class {ColourRGB} ColorRGB = ColourRGB end Only parse a message's timestamp if there truly is one present (MESSAGE_UPDATE doesn't have one) # frozen_string_literal: true # These classes hold relevant Discord data, such as messages or channels. require 'ostruct' require 'discordrb/permissions' require 'discordrb/api' require 'discordrb/events/message' require 'time' require 'base64' # Discordrb module module Discordrb # The unix timestamp Discord IDs are based on DISCORD_EPOCH = 1_420_070_400_000 # Compares two objects based on IDs - either the objects' IDs are equal, or one object is equal to the other's ID. def self.id_compare(one_id, other) other.respond_to?(:resolve_id) ? (one_id.resolve_id == other.resolve_id) : (one_id == other) end # The maximum length a Discord message can have CHARACTER_LIMIT = 2000 # Splits a message into chunks of 2000 characters. Attempts to split by lines if possible. # @param msg [String] The message to split. # @return [Array<String>] the message split into chunks def self.split_message(msg) # If the messages is empty, return an empty array return [] if msg.empty? # Split the message into lines lines = msg.lines # Turn the message into a "triangle" of consecutively longer slices, for example the array [1,2,3,4] would become # [ # [1], # [1, 2], # [1, 2, 3], # [1, 2, 3, 4] # ] tri = [*0..(lines.length - 1)].map { |i| lines.combination(i + 1).first } # Join the individual elements together to get an array of strings with consecutively more lines joined = tri.map { |e| e.join("\n") } # Find the largest element that is still below the character limit, or if none such element exists return the first ideal = joined.max_by { |e| e.length > CHARACTER_LIMIT ? -1 : e.length } # If it's still larger than the character limit (none was smaller than it) split it into slices with the length # being the character limit, otherwise just return an array with one element ideal_ary = (ideal.length > CHARACTER_LIMIT) ? ideal.chars.each_slice(CHARACTER_LIMIT).map(&:join) : [ideal] # Slice off the ideal part and strip newlines rest = msg[ideal.length..-1].strip # If none remains, return an empty array -> we're done return [] unless rest # Otherwise, call the method recursively to split the rest of the string and add it onto the ideal array ideal_ary + split_message(rest) end # Mixin for objects that have IDs module IDObject # @return [Integer] the ID which uniquely identifies this object across Discord. attr_reader :id alias_method :resolve_id, :id # ID based comparison def ==(other) Discordrb.id_compare(@id, other) end # Estimates the time this object was generated on based on the beginning of the ID. This is fairly accurate but # shouldn't be relied on as Discord might change its algorithm at any time # @return [Time] when this object was created at def creation_time # Milliseconds ms = (@id >> 22) + DISCORD_EPOCH Time.at(ms / 1000.0) end end # Mixin for the attributes users should have module UserAttributes # @return [String] this user's username attr_reader :username alias_method :name, :username # @return [String] this user's discriminator which is used internally to identify users with identical usernames. attr_reader :discriminator alias_method :discrim, :discriminator alias_method :tag, :discriminator alias_method :discord_tag, :discriminator # @return [true, false] whether this user is a Discord bot account attr_reader :bot_account alias_method :bot_account?, :bot_account # @return [String] the ID of this user's current avatar, can be used to generate an avatar URL. # @see #avatar_url attr_reader :avatar_id # Utility function to mention users in messages # @return [String] the mention code in the form of <@id> def mention "<@#{@id}>" end # Utility function to get Discord's distinct representation of a user, i. e. username + discriminator # @return [String] distinct representation of user def distinct "#{@username}##{@discriminator}" end # Utility function to get a user's avatar URL. # @return [String] the URL to the avatar image. def avatar_url API.avatar_url(@id, @avatar_id) end end # User on Discord, including internal data like discriminators class User include IDObject include UserAttributes # @!attribute [r] status # @return [Symbol] the current online status of the user (`:online`, `:offline` or `:idle`) attr_accessor :status # @!attribute [r] game # @return [String, nil] the game the user is currently playing, or `nil` if none is being played. attr_accessor :game def initialize(data, bot) @bot = bot @username = data['username'] @id = data['id'].to_i @discriminator = data['discriminator'] @avatar_id = data['avatar'] @roles = {} @bot_account = false @bot_account = true if data['bot'] @status = :offline end # Get a user's PM channel or send them a PM # @overload pm # Creates a private message channel for this user or returns an existing one if it already exists # @return [Channel] the PM channel to this user. # @overload pm(content) # Sends a private to this user. # @param content [String] The content to send. # @return [Message] the message sent to this user. def pm(content = nil) if content # Recursively call pm to get the channel, then send a message to it channel = pm channel.send_message(content) else # If no message was specified, return the PM channel @bot.private_channel(@id) end end # Set the user's name # @note for internal use only # @!visibility private def update_username(username) @username = username end # Add an await for a message from this user. Specifically, this adds a global await for a MessageEvent with this # user's ID as a :from attribute. # @see Bot#add_await def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { from: @id }.merge(attributes), &block) end # Gets the member this user is on a server # @param server [Server] The server to get the member for # @return [Member] this user as a member on a particular server def on(server) id = server.resolve_id @bot.server(id).member(@id) end # Is the user the bot? # @return [true, false] whether this user is the bot def current_bot? @bot.bot_user.id == @id end # The inspect method is overwritten to give more useful output def inspect "<User username=#{@username} id=#{@id} discriminator=#{@discriminator}>" end end # Mixin for the attributes members and private members should have module MemberAttributes # @return [true, false] whether this member is muted server-wide. attr_reader :mute alias_method :muted?, :mute # @return [true, false] whether this member is deafened server-wide. attr_reader :deaf alias_method :deafened?, :deaf # @return [Time] when this member joined the server. attr_reader :joined_at # @return [Array<Role>] the roles this member has. attr_reader :roles # @return [Server] the server this member is on. attr_reader :server # @return [Channel] the voice channel the user is in. attr_reader :voice_channel end # Mixin to calculate resulting permissions from overrides etc. module PermissionCalculator # Checks whether this user can do the particular action, regardless of whether it has the permission defined, # through for example being the server owner or having the Manage Roles permission # @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list. # @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked. # @return [true, false] whether or not this user has the permission. def permission?(action, channel = nil) # If the member is the server owner, it irrevocably has all permissions. return true if owner? # First, check whether the user has Manage Roles defined. # (Coincidentally, Manage Permissions is the same permission as Manage Roles, and a # Manage Permissions deny overwrite will override Manage Roles, so we can just check for # Manage Roles once and call it a day.) return true if defined_permission?(:manage_roles, channel) # Otherwise, defer to defined_permission defined_permission?(action, channel) end # Checks whether this user has a particular permission defined (i. e. not implicit, through for example # Manage Roles) # @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list. # @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked. # @return [true, false] whether or not this user has the permission defined. def defined_permission?(action, channel = nil) # Get the permission the user's roles have role_permission = defined_role_permission?(action, channel) # Once we have checked the role permission, we have to check the channel overrides for the # specific user user_specific_override = permission_overwrite(action, channel, id) # Use the ID reader as members have no ID instance variable # Merge the two permissions - if an override is defined, it has to be allow, otherwise we only care about the role return role_permission unless user_specific_override user_specific_override == :allow end # Define methods for querying permissions Discordrb::Permissions::Flags.each_value do |flag| define_method "can_#{flag}?" do |channel = nil| permission? flag, channel end end private def defined_role_permission?(action, channel) # For each role, check if # (1) the channel explicitly allows or permits an action for the role and # (2) if the user is allowed to do the action if the channel doesn't specify @roles.reduce(false) do |can_act, role| # Get the override defined for the role on the channel channel_allow = permission_overwrite(action, channel, role.id) can_act = if channel_allow # If the channel has an override, check whether it is an allow - if yes, # the user can act, if not, it can't channel_allow == :allow else # Otherwise defer to the role role.permissions.instance_variable_get("@#{action}") || can_act end can_act end end def permission_overwrite(action, channel, id) # If no overwrites are defined, or no channel is set, no overwrite will be present return nil unless channel && channel.permission_overwrites[id] # Otherwise, check the allow and deny objects allow = channel.permission_overwrites[id].allow deny = channel.permission_overwrites[id].deny if allow.instance_variable_get("@#{action}") :allow elsif deny.instance_variable_get("@#{action}") :deny end # If there's no variable defined, nil will implicitly be returned end end # A member is a user on a server. It differs from regular users in that it has roles, voice statuses and things like # that. class Member < DelegateClass(User) include MemberAttributes # @!visibility private def initialize(data, server, bot) @bot = bot @user = bot.ensure_user(data['user']) super @user # Initialize the delegate class # Somehow, Discord doesn't send the server ID in the standard member format... raise ArgumentError, 'Cannot create a member without any information about the server!' if server.nil? && data['guild_id'].nil? @server = server || bot.server(data['guild_id'].to_i) # Initialize the roles by getting the roles from the server one-by-one update_roles(data['roles']) @deaf = data['deaf'] @mute = data['mute'] @joined_at = data['joined_at'] ? Time.parse(data['joined_at']) : nil end # @return [true, false] whether this member is the server owner. def owner? @server.owner == self end # Update this member's roles # @note For internal use only. # @!visibility private def update_roles(roles) @roles = roles.map do |role_id| @server.role(role_id.to_i) end end # Update this member's voice state # @note For internal use only. # @!visibility private def update_voice_state(channel, mute, deaf, self_mute, self_deaf) @voice_channel = channel @mute = mute @deaf = deaf @self_mute = self_mute @self_deaf = self_deaf end include PermissionCalculator # Overwriting inspect for debug purposes def inspect "<Member user=#{@user.inspect} server=#{@server.inspect} joined_at=#{@joined_at} roles=#{@roles.inspect} voice_channel=#{@voice_channel.inspect} mute=#{@mute} deaf=#{@deaf} self_mute=#{@self_mute} self_deaf=#{@self_deaf}>" end end # Recipients are members on private channels - they exist for completeness purposes, but all # the attributes will be empty. class Recipient < DelegateClass(User) include MemberAttributes # @return [Channel] the private channel this recipient is the recipient of. attr_reader :channel # @!visibility private def initialize(user, channel, bot) @bot = bot @channel = channel raise ArgumentError, 'Tried to create a recipient for a public channel!' unless @channel.private? @user = user super @user # Member attributes @mute = @deaf = @self_mute = @self_deaf = false @voice_channel = nil @server = nil @roles = [] @joined_at = @channel.creation_time end # Overwriting inspect for debug purposes def inspect "<Recipient user=#{@user.inspect} channel=#{@channel.inspect}>" end end # This class is a special variant of User that represents the bot's user profile (things like email addresses and the avatar). # It can be accessed using {Bot#profile}. class Profile < User def initialize(data, bot, email, password) super(data, bot) @email = email @password = password end # Whether or not the user is the bot. The Profile can only ever be the bot user, so this always returns true. # @return [true] def current_bot? true end # Sets the bot's username. # @param username [String] The new username. def username=(username) update_profile_data(username: username) end # Sets the bot's email address. If you use this method, make sure that the login email in the script matches this # one afterwards, so the bot doesn't have any trouble logging in in the future. # @param email [String] The new email address. def email=(email) update_profile_data(email: email) end # Changes the bot's password. This will invalidate all tokens so you will have to relog the bot. # @param password [String] The new password. def password=(password) update_profile_data(new_password: password) end # Changes the bot's avatar. # @param avatar [String, #read] A JPG file to be used as the avatar, either # something readable (e. g. File) or as a data URL. def avatar=(avatar) if avatar.respond_to? :read avatar_string = 'data:image/jpg;base64,' avatar_string += Base64.strict_encode64(avatar.read) update_profile_data(avatar: avatar_string) else update_profile_data(avatar: avatar) end end # Updates the cached profile data with the new one. # @note For internal use only. # @!visibility private def update_data(new_data) @email = new_data[:email] || @email @password = new_data[:new_password] || @password @username = new_data[:username] || @username @avatar_id = new_data[:avatar_id] || @avatar_id end # The inspect method is overwritten to give more useful output def inspect "<Profile email=#{@email} user=#{super}>" end private def update_profile_data(new_data) API.update_user(@bot.token, new_data[:email] || @email, @password, new_data[:username] || @username, new_data[:avatar], new_data[:new_password] || nil) update_data(new_data) end end # A Discord role that contains permissions and applies to certain users class Role include IDObject # @return [Permissions] this role's permissions. attr_reader :permissions # @return [String] this role's name ("new role" if it hasn't been changed) attr_reader :name # @return [true, false] whether or not this role should be displayed separately from other users attr_reader :hoist # @return [ColourRGB] the role colour attr_reader :colour alias_method :color, :colour # This class is used internally as a wrapper to a Role object that allows easy writing of permission data. class RoleWriter # @!visibility private def initialize(role, token) @role = role @token = token end # Write the specified permission data to the role, without updating the permission cache # @param bits [Integer] The packed permissions to write. def write(bits) @role.send(:packed=, bits, false) end end # @!visibility private def initialize(data, bot, server = nil) @bot = bot @server = server @permissions = Permissions.new(data['permissions'], RoleWriter.new(self, @bot.token)) @name = data['name'] @id = data['id'].to_i @hoist = data['hoist'] @colour = ColourRGB.new(data['color']) end # Updates the data cache from another Role object # @note For internal use only # @!visibility private def update_from(other) @permissions = other.permissions @name = other.name @hoist = other.hoist @colour = other.colour end # Updates the data cache from a hash containing data # @note For internal use only # @!visibility private def update_data(new_data) @name = new_data[:name] || new_data['name'] || @name @hoist = new_data['hoist'] unless new_data['hoist'].nil? @hoist = new_data[:hoist] unless new_data[:hoist].nil? @colour = new_data[:colour] || (new_data['color'] ? ColourRGB.new(new_data['color']) : @colour) end # Sets the role name to something new # @param name [String] The name that should be set def name=(name) update_role_data(name: name) end # Changes whether or not this role is displayed at the top of the user list # @param hoist [true, false] The value it should be changed to def hoist=(hoist) update_role_data(hoist: hoist) end # Sets the role colour to something new # @param colour [ColourRGB] The new colour def colour=(colour) update_role_data(colour: colour) end alias_method :color=, :colour= # Changes the internal packed permissions # @note For internal use only # @!visibility private def packed=(packed, update_perms = true) update_role_data(permissions: packed) @permissions.bits = packed if update_perms end # Delets this role. This cannot be undone without recreating the role! def delete API.delete_role(@bot.token, @server.id, @id) @server.delete_role(@id) end # The inspect method is overwritten to give more useful output def inspect "<Role name=#{@name} permissions=#{@permissions.inspect} hoist=#{@hoist} colour=#{@colour.inspect} server=#{@server.inspect}>" end private def update_role_data(new_data) API.update_role(@bot.token, @server.id, @id, new_data[:name] || @name, (new_data[:colour] || @colour).combined, new_data[:hoist].nil? ? false : !@hoist.nil?, new_data[:permissions] || @permissions.bits) update_data(new_data) end end # A Discord invite to a channel class Invite # @return [Channel] the channel this invite references. attr_reader :channel # @return [Server] the server this invite references. attr_reader :server # @return [Integer] the amount of uses left on this invite. attr_reader :uses # @return [User, nil] the user that made this invite. May also be nil if the user can't be determined. attr_reader :inviter # @return [true, false] whether or not this invite is temporary. attr_reader :temporary # @return [true, false] whether this invite is still valid. attr_reader :revoked # @return [true, false] whether this invite is in xkcd format (i. e. "Human readable" in the invite settings) attr_reader :xkcd # @return [String] this invite's code attr_reader :code alias_method :max_uses, :uses alias_method :user, :inviter alias_method :temporary?, :temporary alias_method :revoked?, :revoked alias_method :xkcd?, :xkcd # @!visibility private def initialize(data, bot) @bot = bot @channel = Channel.new(data['channel'], bot) @server = Server.new(data['guild'], bot) @uses = data['uses'] @inviter = data['inviter'] ? (@bot.user(data['inviter']['id'].to_i) || User.new(data['inviter'], bot)) : nil @temporary = data['temporary'] @revoked = data['revoked'] @xkcd = data['xkcdpass'] @code = data['code'] end # Code based comparison def ==(other) other.respond_to?(:code) ? (@code == other.code) : (@code == other) end # Deletes this invite def delete API.delete_invite(@bot.token, @code) end alias_method :revoke, :delete # The inspect method is overwritten to give more useful output def inspect "<Invite code=#{@code} channel=#{@channel} uses=#{@uses} temporary=#{@temporary} revoked=#{@revoked} xkcd=#{@xkcd}>" end end # A Discord channel, including data like the topic class Channel # The type string that stands for a text channel # @see Channel#type TEXT_TYPE = 'text'.freeze # The type string that stands for a voice channel # @see Channel#type VOICE_TYPE = 'voice'.freeze include IDObject # @return [String] this channel's name. attr_reader :name # @return [Server, nil] the server this channel is on. If this channel is a PM channel, it will be nil. attr_reader :server # @return [String] the type of this channel (currently either 'text' or 'voice') attr_reader :type # @return [Recipient, nil] the recipient of the private messages, or nil if this is not a PM channel attr_reader :recipient # @return [String] the channel's topic attr_reader :topic # @return [Integer] the channel's position on the channel list attr_reader :position # This channel's permission overwrites, represented as a hash of role/user ID to an OpenStruct which has the # `allow` and `deny` properties which are {Permissions} objects respectively. # @return [Hash<Integer => OpenStruct>] the channel's permission overwrites attr_reader :permission_overwrites # @return [true, false] whether or not this channel is a PM channel. def private? @server.nil? end # @return [String] a string that will mention the channel as a clickable link on Discord. def mention "<##{@id}>" end # @!visibility private def initialize(data, bot, server = nil) @bot = bot # data is a sometimes a Hash and othertimes an array of Hashes, you only want the last one if it's an array data = data[-1] if data.is_a?(Array) @id = data['id'].to_i @type = data['type'] || TEXT_TYPE @topic = data['topic'] @position = data['position'] @is_private = data['is_private'] if @is_private recipient_user = bot.ensure_user(data['recipient']) @recipient = Recipient.new(recipient_user, self, bot) @name = @recipient.username else @name = data['name'] @server = if server server else bot.server(data['guild_id'].to_i) end end # Populate permission overwrites @permission_overwrites = {} return unless data['permission_overwrites'] data['permission_overwrites'].each do |element| role_id = element['id'].to_i deny = Permissions.new(element['deny']) allow = Permissions.new(element['allow']) @permission_overwrites[role_id] = OpenStruct.new @permission_overwrites[role_id].deny = deny @permission_overwrites[role_id].allow = allow end end # @return [true, false] whether or not this channel is a text channel def text? @type == TEXT_TYPE end # @return [true, false] whether or not this channel is a voice channel def voice? @type == VOICE_TYPE end # Sends a message to this channel. # @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error. # @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech. # @return [Message] the message that was sent. def send_message(content, tts = false) @bot.send_message(@id, content, tts) end # Sends multiple messages to a channel # @param content [Array<String>] The messages to send. def send_multiple(content) content.each { |e| send_message(e) } end # Splits a message into chunks whose length is at most the Discord character limit, then sends them individually. # Useful for sending long messages, but be wary of rate limits! def split_send(content) send_multiple(Discordrb.split_message(content)) end # Sends a file to this channel. If it is an image, it will be embedded. # @param file [File] The file to send. There's no clear size limit for this, you'll have to attempt it for yourself (most non-image files are fine, large images may fail to embed) def send_file(file) @bot.send_file(@id, file) end # Permanently deletes this channel def delete API.delete_channel(@bot.token, @id) end # Sets this channel's name. The name must be alphanumeric with dashes, unless this is a voice channel (then there are no limitations) # @param name [String] The new name. def name=(name) @name = name update_channel_data end # Sets this channel's topic. # @param topic [String] The new topic. def topic=(topic) @topic = topic update_channel_data end # Sets this channel's position in the list. # @param position [Integer] The new position. def position=(position) @position = position update_channel_data end # Defines a permission overwrite for this channel that sets the specified thing to the specified allow and deny # permission sets, or change an existing one. # @param thing [User, Role] What to define an overwrite for. # @param allow [#bits, Permissions, Integer] The permission sets that should receive an `allow` override (i. e. a # green checkmark on Discord) # @param deny [#bits, Permissions, Integer] The permission sets that should receive a `deny` override (i. e. a red # cross on Discord) # @example Define a permission overwrite for a user that can then mention everyone and use TTS, but not create any invites # allow = Discordrb::Permissions.new # allow.can_mention_everyone = true # allow.can_send_tts_messages = true # # deny = Discordrb::Permissions.new # deny.can_create_instant_invite = true # # channel.define_overwrite(user, allow, deny) def define_overwrite(thing, allow, deny) allow_bits = allow.respond_to?(:bits) ? allow.bits : allow deny_bits = deny.respond_to?(:bits) ? deny.bits : deny if thing.is_a? User API.update_user_overrides(@bot.token, @id, thing.id, allow_bits, deny_bits) elsif thing.is_a? Role API.update_role_overrides(@bot.token, @id, thing.id, allow_bits, deny_bits) end end # Updates the cached data from another channel. # @note For internal use only # @!visibility private def update_from(other) @topic = other.topic @name = other.name @recipient = other.recipient @permission_overwrites = other.permission_overwrites end # The list of users currently in this channel. This is mostly useful for a voice channel, for a text channel it will # just return the users on the server that are online. # @return [Array<Member>] the users in this channel def users if @type == 'text' @server.members.select { |u| u.status != :offline } else @server.members.select do |user| user.voice_channel.id == @id if user.voice_channel end end end # Retrieves some of this channel's message history. # @param amount [Integer] How many messages to retrieve. This must be less than or equal to 100, if it is higher # than 100 it will be treated as 100 on Discord's side. # @param before_id [Integer] The ID of the most recent message the retrieval should start at, or nil if it should # start at the current message. # @param after_id [Integer] The ID of the oldest message the retrieval should start at, or nil if it should start # as soon as possible with the specified amount. # @return [Array<Message>] the retrieved messages. def history(amount, before_id = nil, after_id = nil) logs = API.channel_log(@bot.token, @id, amount, before_id, after_id) JSON.parse(logs).map { |message| Message.new(message, @bot) } end # Deletes the last N messages on this channel. # @note Each delete request is performed in a separate thread for performance reasons, so if a large number of # messages are pruned, many threads will be created. # @param amount [Integer] How many messages to delete. Must be 100 or less (Discord limitation) # @raise [ArgumentError] if more than 100 messages are requested. def prune(amount) raise ArgumentError, "Can't prune more than 100 messages!" if amount > 100 threads = [] history(amount).each do |message| threads << Thread.new { message.delete } end # Make sure all requests have finished threads.each(&:join) # Delete the threads threads.map! { nil } end # Updates the cached permission overwrites # @note For internal use only # @!visibility private def update_overwrites(overwrites) @permission_overwrites = overwrites end # Add an {Await} for a message in this channel. This is identical in functionality to adding a # {Discordrb::Events::MessageEvent} await with the `in` attribute as this channel. # @see Bot#add_await def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { in: @id }.merge(attributes), &block) end # Creates a new invite to this channel. # @param max_age [Integer] How many seconds this invite should last. # @param max_uses [Integer] How many times this invite should be able to be used. # @param temporary [true, false] Whether membership should be temporary (kicked after going offline). # @param xkcd [true, false] Whether or not the invite should be human-readable. # @return [Invite] the created invite. def make_invite(max_age = 0, max_uses = 0, temporary = false, xkcd = false) response = API.create_invite(@bot.token, @id, max_age, max_uses, temporary, xkcd) Invite.new(JSON.parse(response), @bot) end # Starts typing, which displays the typing indicator on the client for five seconds. # If you want to keep typing you'll have to resend this every five seconds. (An abstraction # for this will eventually be coming) def start_typing API.start_typing(@bot.token, @id) end alias_method :send, :send_message alias_method :message, :send_message alias_method :invite, :make_invite # The inspect method is overwritten to give more useful output def inspect "<Channel name=#{@name} id=#{@id} topic=\"#{@topic}\" type=#{@type} position=#{@position} server=#{@server}>" end private def update_channel_data API.update_channel(@bot.token, @id, @name, @topic, @position) end end # An attachment to a message class Attachment include IDObject # @return [Message] the message this attachment belongs to. attr_reader :message # @return [String] the CDN URL this attachment can be downloaded at. attr_reader :url # @return [String] the attachment's proxy URL - I'm not sure what exactly this does, but I think it has something to # do with CDNs attr_reader :proxy_url # @return [String] the attachment's filename. attr_reader :filename # @return [Integer] the attachment's file size in bytes. attr_reader :size # @return [Integer, nil] the width of an image file, in pixels, or nil if the file is not an image. attr_reader :width # @return [Integer, nil] the height of an image file, in pixels, or nil if the file is not an image. attr_reader :height # @!visibility private def initialize(data, message, bot) @bot = bot @message = message @url = data['url'] @proxy_url = data['proxy_url'] @filename = data['filename'] @size = data['size'] @width = data['width'] @height = data['height'] end # @return [true, false] whether this file is an image file. def image? !(@width.nil? || @height.nil?) end end # A message on Discord that was sent to a text channel class Message include IDObject # @return [String] the content of this message. attr_reader :content # @return [Member] the user that sent this message. attr_reader :author # @return [Channel] the channel in which this message was sent. attr_reader :channel # @return [Time] the timestamp at which this message was sent. attr_reader :timestamp # @return [Array<User>] the users that were mentioned in this message. attr_reader :mentions # @return [Array<Attachment>] the files attached to this message. attr_reader :attachments alias_method :user, :author alias_method :text, :content alias_method :to_s, :content # @!visibility private def initialize(data, bot) @bot = bot @content = data['content'] @channel = bot.channel(data['channel_id'].to_i) @author = if data['author'] if @channel.private? # Turn the message user into a recipient - we can't use the channel recipient # directly because the bot may also send messages to the channel Recipient.new(bot.user(data['author']['id'].to_i), @channel, bot) else @channel.server.member(data['author']['id'].to_i) end end @timestamp = Time.parse(data['timestamp']) if data['timestamp'] @id = data['id'].to_i @mentions = [] data['mentions'].each do |element| @mentions << bot.ensure_user(element) end if data['mentions'] @attachments = data['attachments'].map { |e| Attachment.new(e, self, @bot) } end # Replies to this message with the specified content. # @see Channel#send_message def reply(content) @channel.send_message(content) end # Edits this message to have the specified content instead. # @param new_content [String] the new content the message should have. # @return [Message] the resulting message. def edit(new_content) response = API.edit_message(@bot.token, @channel.id, @id, new_content) Message.new(JSON.parse(response), @bot) end # Deletes this message. def delete API.delete_message(@bot.token, @channel.id, @id) nil end # Add an {Await} for a message with the same user and channel. # @see Bot#add_await def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { from: @author.id, in: @channel.id }.merge(attributes), &block) end # @return [true, false] whether this message was sent by the current {Bot}. def from_bot? @author.current_bot? end # The inspect method is overwritten to give more useful output def inspect "<Message content=\"#{@content}\" id=#{@id} timestamp=#{@timestamp} author=#{@author} channel=#{@channel}>" end end # Basic attributes a server should have module ServerAttributes # @return [String] this server's name. attr_reader :name # @return [String] the hexadecimal ID used to identify this server's icon. attr_reader :icon_id # Utility function to get the URL for the icon image # @return [String] the URL to the icon image def icon_url API.icon_url(@id, @icon_id) end end # A server on Discord class Server include IDObject include ServerAttributes # @return [String] the region the server is on (e. g. `amsterdam`). attr_reader :region # @return [Member] The server owner. attr_reader :owner # @return [Array<Channel>] an array of all the channels (text and voice) on this server. attr_reader :channels # @return [Array<Role>] an array of all the roles created on this server. attr_reader :roles # @return [true, false] whether or not this server is large (members > 100). If it is, # it means the members list may be inaccurate for a couple seconds after starting up the bot. attr_reader :large alias_method :large?, :large # @return [Integer] the absolute number of members on this server, offline or not. attr_reader :member_count # @return [Integer] the amount of time after which a voice user gets moved into the AFK channel, in seconds. attr_reader :afk_timeout # @return [Channel, nil] the AFK voice channel of this server, or nil if none is set attr_reader :afk_channel # @!visibility private def initialize(data, bot) @bot = bot @owner_id = data['owner_id'].to_i @id = data['id'].to_i update_data(data) @large = data['large'] @member_count = data['member_count'] @members = {} process_roles(data['roles']) process_members(data['members']) process_presences(data['presences']) process_channels(data['channels']) process_voice_states(data['voice_states']) # Whether this server's members have been chunked (resolved using op 8 and GUILD_MEMBERS_CHUNK) yet @chunked = false @processed_chunk_members = 0 @owner = member(@owner_id) end # @return [Channel] The default channel on this server (usually called #general) def default_channel @bot.channel(@id) end alias_method :general_channel, :default_channel # Gets a role on this server based on its ID. # @param id [Integer] The role ID to look for. def role(id) @roles.find { |e| e.id == id } end # Gets a member on this server based on user ID # @param id [Integer] The user ID to look for def member(id) id = id.resolve_id return @members[id] if member_cached?(id) member = bot.member(@id, id) @members[id] = member end # @return [Array<Member>] an array of all the members on this server. def members return @members.values if @chunked @bot.debug("Members for server #{@id} not chunked yet - initiating") @bot.request_chunks(@id) sleep 0.05 until @chunked @members.values end alias_method :users, :members # Adds a role to the role cache # @note For internal use only # @!visibility private def add_role(role) @roles << role end # Removes a role from the role cache # @note For internal use only # @!visibility private def delete_role(role_id) @roles.reject! { |r| r.id == role_id } @members.each do |_, member| new_roles = member.roles.reject { |r| r.id == role_id } member.update_roles(new_roles) end @channels.each do |channel| overwrites = channel.permission_overwrites.reject { |id, _| id == role_id } channel.update_overwrites(overwrites) end end # Adds a member to the member cache. # @note For internal use only # @!visibility private def add_member(member) @members[member.id] = member @member_count += 1 end # Removes a member from the member cache. # @note For internal use only # @!visibility private def delete_member(user_id) @members.delete(user_id) @member_count -= 1 end # Checks whether a member is cached # @note For internal use only # @!visibility private def member_cached?(user_id) @members.include?(user_id) end # Adds a member to the cache # @note For internal use only # @!visibility private def cache_member(member) @members[member.id] = member end # Creates a channel on this server with the given name. # @return [Channel] the created channel. def create_channel(name, type = 'text') response = API.create_channel(@bot.token, @id, name, type) Channel.new(JSON.parse(response), @bot) end # Creates a role on this server which can then be modified. It will be initialized (on Discord's side) # with the regular role defaults the client uses, i. e. name is "new role", permissions are the default, # colour is the default etc. # @return [Role] the created role. def create_role response = API.create_role(@bot.token, @id) role = Role.new(JSON.parse(response), @bot, self) @roles << role role end # @return [Array<User>] a list of banned users on this server. def bans users = JSON.parse(API.bans(@bot.token, @id)) users.map { |e| User.new(e['user'], @bot) } end # Bans a user from this server. # @param user [User] The user to ban. # @param message_days [Integer] How many days worth of messages sent by the user should be deleted. def ban(user, message_days = 0) API.ban_user(@bot.token, @id, user.id, message_days) end # Unbans a previously banned user from this server. # @param user [User] The user to unban. def unban(user) API.unban_user(@bot.token, @id, user.id) end # Kicks a user from this server. # @param user [User] The user to kick. def kick(user) API.kick_user(@bot.token, @id, user.id) end # Forcibly moves a user into a different voice channel. Only works if the bot has the permission needed. # @param user [User] The user to move. # @param channel [Channel] The voice channel to move into. def move(user, channel) API.move_user(@bot.token, @id, user.id, channel.id) end # Deletes this server. Be aware that this is permanent and impossible to undo, so be careful! def delete API.delete_server(@bot.token, @id) end # Leave the server def leave API.leave_server(@bot.token, @id) end # Transfers server ownership to another user. # @param user [User] The user who should become the new owner. def owner=(user) API.transfer_ownership(@bot.token, @id, user.id) end # Sets the server's name. # @param name [String] The new server name. def name=(name) update_server_data(name: name) end # Moves the server to another region. This will cause a voice interruption of at most a second. # @param region [String] The new region the server should be in. def region=(region) update_server_data(region: region.to_s) end # Sets the server's icon. # @param icon [String, #read] The new icon, in base64-encoded JPG format. def icon=(icon) if icon.respond_to? :read icon_string = 'data:image/jpg;base64,' icon_string += Base64.strict_encode64(icon.read) update_server_data(icon: icon_string) else update_server_data(icon: icon) end end # Sets the server's AFK channel. # @param afk_channel [Channel, nil] The new AFK channel, or `nil` if there should be none set. def afk_channel=(afk_channel) update_server_data(afk_channel_id: afk_channel.resolve_id) end # @deprecated Use #afk_channel= with the ID instead. def afk_channel_id=(afk_channel_id) update_server_data(afk_channel_id: afk_channel_id) end # Sets the amount of time after which a user gets moved into the AFK channel. # @param afk_timeout [Integer] The AFK timeout, in seconds. def afk_timeout=(afk_timeout) update_server_data(afk_timeout: afk_timeout) end # Processes a GUILD_MEMBERS_CHUNK packet, specifically the members field # @note For internal use only # @!visibility private def process_chunk(members) process_members(members) @processed_chunk_members += members.length LOGGER.debug("Processed one chunk on server #{@id} - length #{members.length}") # Don't bother with the rest of the method if it's not truly the last packet return unless @processed_chunk_members == @member_count LOGGER.debug("Finished chunking server #{@id}") # Reset everything to normal @chunked = true @processed_chunk_members = 0 end # Updates the cached data with new data # @note For internal use only # @!visibility private def update_data(new_data) @name = new_data[:name] || new_data['name'] || @name @region = new_data[:region] || new_data['region'] || @region @icon_id = new_data[:icon] || new_data['icon'] || @icon_id @afk_timeout = new_data[:afk_timeout] || new_data['afk_timeout'].to_i || @afk_timeout @afk_channel_id = new_data[:afk_channel_id] || new_data['afk_channel_id'].to_i || @afk_channel.id @afk_channel = @bot.channel(@afk_channel_id, self) if @afk_channel_id != 0 && (!@afk_channel || @afk_channel_id != @afk_channel.id) end # The inspect method is overwritten to give more useful output def inspect "<Server name=#{@name} id=#{@id} large=#{@large} region=#{@region} owner=#{@owner} afk_channel_id=#{@afk_channel_id} afk_timeout=#{@afk_timeout}>" end private def update_server_data(new_data) API.update_server(@bot.token, @id, new_data[:name] || @name, new_data[:region] || @region, new_data[:icon_id] || @icon_id, new_data[:afk_channel_id] || @afk_channel_id, new_data[:afk_timeout] || @afk_timeout) update_data(new_data) end def process_roles(roles) # Create roles @roles = [] @roles_by_id = {} return unless roles roles.each do |element| role = Role.new(element, @bot, self) @roles << role @roles_by_id[role.id] = role end end def process_members(members) return unless members members.each do |element| member = Member.new(element, self, @bot) @members[member.id] = member end end def process_presences(presences) # Update user statuses with presence info return unless presences presences.each do |element| next unless element['user'] user_id = element['user']['id'].to_i user = @members[user_id] if user user.status = element['status'].to_sym user.game = element['game'] ? element['game']['name'] : nil end end end def process_channels(channels) @channels = [] @channels_by_id = {} return unless channels channels.each do |element| channel = Channel.new(element, @bot, self) @channels << channel @channels_by_id[channel.id] = channel end end def process_voice_states(voice_states) return unless voice_states voice_states.each do |element| user_id = element['user_id'].to_i member = @members[user_id] next unless member channel_id = element['channel_id'].to_i channel = channel_id ? @channels_by_id[channel_id] : nil member.update_voice_state( channel, element['mute'], element['deaf'], element['self_mute'], element['self_deaf']) end end end # A colour (red, green and blue values). Used for role colours. If you prefer the American spelling, the alias # {ColorRGB} is also available. class ColourRGB # @return [Integer] the red part of this colour (0-255). attr_reader :red # @return [Integer] the green part of this colour (0-255). attr_reader :green # @return [Integer] the blue part of this colour (0-255). attr_reader :blue # @return [Integer] the colour's RGB values combined into one integer. attr_reader :combined # Make a new colour from the combined value. # @param combined [Integer] The colour's RGB values combined into one integer def initialize(combined) @combined = combined @red = (combined >> 16) & 0xFF @green = (combined >> 8) & 0xFF @blue = combined & 0xFF end end # Alias for the class {ColourRGB} ColorRGB = ColourRGB end
# These classes hold relevant Discord data, such as messages or channels. require 'ostruct' require 'discordrb/permissions' require 'discordrb/api' require 'discordrb/games' require 'discordrb/events/message' require 'base64' # Discordrb module module Discordrb # User on Discord, including internal data like discriminators class User attr_reader :username, :id, :discriminator, :avatar, :voice_channel, :roles attr_accessor :status, :game, :server_mute, :server_deaf, :self_mute, :self_deaf # @roles is a hash of user roles: # Key: Server ID # Value: Array of roles. alias_method :name, :username def initialize(data, bot) @bot = bot @username = data['username'] @id = data['id'].to_i @discriminator = data['discriminator'] @avatar = data['avatar'] @roles = {} @status = :offline end # Utility function to mention users in messages def mention "<@#{@id}>" end # Utility function to send a PM def pm(content = nil) if content # Recursively call pm to get the channel, then send a message to it channel = pm channel.send_message(content) else # If no message was specified, return the PM channel @bot.private_channel(@id) end end # Move a user into a voice channel def move(to_channel) return if to_channel && to_channel.type != 'voice' @voice_channel = to_channel end # Set this user's roles def update_roles(server, roles) @roles[server.id] = roles end # Merge this user's roles with the roles from another instance of this user (from another server) def merge_roles(server, roles) if @roles[server.id] @roles[server.id] = (@roles[server.id] + roles).uniq else @roles[server.id] = roles end end # Delete a specific server from the roles (in case a user leaves a server) def delete_roles(server_id) @roles.delete(server_id) end # Add an await for a message from this user def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { from: @id }.merge(attributes), &block) end # Is the user the bot? def bot? @bot.bot_user.id == @id end # Determine if the user has permission to do an action # action is a permission from Permissions::Flags. # channel is the channel in which the action takes place (not applicable for server-wide actions). def permission?(action, server, channel = nil) # For each role, check if # (1) the channel explicitly allows or permits an action for the role and # (2) if the user is allowed to do the action if the channel doesn't specify return false unless @roles[server.id] @roles[server.id].reduce(false) do |can_act, role| channel_allow = nil if channel && channel.permission_overwrites[role.id] allow = channel.permission_overwrites[role.id].allow deny = channel.permission_overwrites[role.id].deny if allow.instance_variable_get("@#{action}") channel_allow = true elsif deny.instance_variable_get("@#{action}") channel_allow = false end # If the channel has nothing to say on the matter, we can defer to the role itself end if channel_allow == false can_act = false elsif channel_allow == true can_act = true else # channel_allow == nil can_act = role.permissions.instance_variable_get("@#{action}") || can_act end can_act end end # Define methods for querying permissions Discordrb::Permissions::Flags.each_value do |flag| define_method "can_#{flag}?" do |server, channel = nil| permission? flag, server, channel end end end # A class that represents the bot user itself and has methods to change stuff class Profile < User def initialize(data, bot, email, password) super(data, bot) @email = email @password = password end def bot? true end def username=(username) update_server_data(username: username) end def email=(email) update_server_data(email: email) end def password=(password) update_server_data(new_password: password) end def avatar=(avatar) if avatar.is_a? File avatar_string = 'data:image/jpg;base64,' avatar_string += Base64.strict_encode64(avatar.read) update_server_data(avatar: avatar_string) else update_server_data(avatar: avatar) end end def update_data(new_data) @email = new_data[:email] || @email @password = new_data[:new_password] || @password @username = new_data[:username] || @username @avatar = new_data[:avatar] || @avatar end private def update_server_data(new_data) API.update_user(@bot.token, new_data[:email] || @email, @password, new_data[:username] || @username, new_data[:avatar] || @avatar, new_data[:new_password] || nil) update_data(new_data) end end # A Discord role that contains permissions and applies to certain users class Role attr_reader :permissions, :name, :id, :hoist, :colour alias_method :color, :colour # Class that writes data for a Permissions object class RoleWriter def initialize(role, token) @role = role @token = token end def write(bits) @role.send(:packed=, bits, false) end end def initialize(data, bot, server = nil) @bot = bot @server = server @permissions = Permissions.new(data['permissions'], RoleWriter.new(self, @bot.token)) @name = data['name'] @id = data['id'].to_i @hoist = data['hoist'] @colour = ColourRGB.new(data['color']) end def update_from(other) @permissions = other.permissions @name = other.name @hoist = other.hoist @colour = other.colour end def update_data(new_data) @name = new_data[:name] || new_data['name'] || @name @hoist = new_data['hoist'] unless new_data['hoist'].nil? @hoist = new_data[:hoist] unless new_data[:hoist].nil? @colour = new_data[:colour] || (new_data['color'] ? ColourRGB.new(new_data['color']) : @colour) end def name=(name) update_role_data(name: name) end def hoist=(hoist) update_role_data(hoist: hoist) end def colour=(colour) update_role_data(colour: colour) end alias_method :color=, :colour= def packed=(packed, update_perms = true) update_role_data(permissions: packed) @permissions.bits = packed if update_perms end def delete API.delete_role(@bot.token, @server.id, @id) @server.delete_role(@id) end private def update_role_data(new_data) API.update_role(@bot.token, @server.id, @id, new_data[:name] || @name, (new_data[:colour] || @colour).combined, !(!(new_data[:hoist].nil? ? new_data[:hoist] : @hoist)), new_data[:permissions] || @permissions.bits) update_data(new_data) end end # A Discord invite to a channel class Invite attr_reader :channel, :uses, :inviter, :temporary, :revoked, :xkcd, :code alias_method :max_uses, :uses alias_method :user, :inviter alias_method :temporary?, :temporary alias_method :revoked?, :revoked alias_method :xkcd?, :xkcd delegate :server, to: :channel def initialize(data, bot) @bot = bot @channel = Channel.new(data['channel'], bot) @uses = data['uses'] @inviter = @bot.user(data['inviter']['id'].to_i) || User.new(data['inviter'], bot) @temporary = data['temporary'] @revoked = data['revoked'] @xkcd = data['xkcdpass'] @code = data['code'] end def delete API.delete_invite(@bot.token, @code) end end # A Discord channel, including data like the topic class Channel attr_reader :name, :server, :type, :id, :is_private, :recipient, :topic, :position, :permission_overwrites def private? @server.nil? end def initialize(data, bot, server = nil) @bot = bot # data is a sometimes a Hash and othertimes an array of Hashes, you only want the last one if it's an array data = data[-1] if data.is_a?(Array) @id = data['id'].to_i @type = data['type'] || 'text' @topic = data['topic'] @position = data['position'] @is_private = data['is_private'] if @is_private @recipient = User.new(data['recipient'], bot) @name = @recipient.username else @name = data['name'] @server = bot.server(data['guild_id'].to_i) @server ||= server end # Populate permission overwrites @permission_overwrites = {} return unless data['permission_overwrites'] data['permission_overwrites'].each do |element| role_id = element['id'].to_i deny = Permissions.new(element['deny']) allow = Permissions.new(element['allow']) @permission_overwrites[role_id] = OpenStruct.new @permission_overwrites[role_id].deny = deny @permission_overwrites[role_id].allow = allow end end def send_message(content) @bot.send_message(@id, content) end def send_file(file) @bot.send_file(@id, file) end def delete API.delete_channel(@bot.token, @id) end def name=(name) @name = name update_channel_data end def topic=(topic) @topic = topic update_channel_data end def position=(position) @position = position update_channel_data end def update_from(other) @topic = other.topic @name = other.name @is_private = other.is_private @recipient = other.recipient @permission_overwrites = other.permission_overwrites end # List of users currently in a channel def users if @type == 'text' @server.members.select { |u| u.status != :offline } else @server.members.select do |user| user.voice_channel.id == @id if user.voice_channel end end end def history(amount, before_id = nil, after_id = nil) logs = API.channel_log(@bot.token, @id, amount, before_id, after_id) JSON.parse(logs).map { |message| Message.new(message, @bot) } end def update_overwrites(overwrites) @permission_overwrites = overwrites end # Add an await for a message in this channel def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { in: @id }.merge(attributes), &block) end def make_invite(max_age = 0, max_uses = 0, temporary = false, xkcd = false) response = API.create_invite(@bot.token, @id, max_age, max_uses, temporary, xkcd) Invite.new(JSON.parse(response), @bot) end # Starts typing, which displays the typing indicator on the client for five seconds. # If you want to keep typing you'll have to resend this every five seconds. (An abstraction # for this will eventually be coming) def start_typing API.start_typing(@bot.token, @id) end alias_method :send, :send_message alias_method :message, :send_message alias_method :invite, :make_invite private def update_channel_data API.update_channel(@bot.token, @id, @name, @topic, @position) end end # A message on Discord that was sent to a text channel class Message attr_reader :content, :author, :channel, :timestamp, :id, :mentions alias_method :user, :author alias_method :text, :content def initialize(data, bot) @bot = bot @content = data['content'] @author = User.new(data['author'], bot) @channel = bot.channel(data['channel_id'].to_i) @timestamp = Time.at(data['timestamp'].to_i) @id = data['id'].to_i @mentions = [] data['mentions'].each do |element| @mentions << User.new(element, bot) end end def reply(content) @channel.send_message(content) end def edit(new_content) API.edit_message(@bot.token, @channel.id, @id, new_content) end def delete API.delete_message(@bot.token, @channel.id, @id) end # Add an await for a message with the same user and channel def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { from: @author.id, in: @channel.id }.merge(attributes), &block) end def from_bot? @author.bot? end end # A server on Discord class Server attr_reader :region, :name, :owner_id, :id, :members, :channels, :roles, :icon, :afk_timeout, :afk_channel_id def initialize(data, bot) @bot = bot @owner_id = data['owner_id'].to_i @id = data['id'].to_i update_data(data) process_roles(data['roles']) process_members(data['members']) process_presences(data['presences']) process_channels(data['channels']) process_voice_states(data['voice_states']) end def process_roles(roles) # Create roles @roles = [] @roles_by_id = {} roles.each do |element| role = Role.new(element, @bot, self) @roles << role @roles_by_id[role.id] = role end end def process_members(members) @members = [] @members_by_id = {} return unless members members.each do |element| user = User.new(element['user'], @bot) @members << user @members_by_id[user.id] = user user_roles = [] element['roles'].each do |e| role_id = e.to_i user_roles << @roles_by_id[role_id] end user.update_roles(self, user_roles) end end def process_presences(presences) # Update user statuses with presence info return unless presences presences.each do |element| next unless element['user'] user_id = element['user']['id'].to_i user = @members_by_id[user_id] if user user.status = element['status'].to_sym user.game = Discordrb::Games.find_game(element['game_id']) end end end def process_channels(channels) @channels = [] @channels_by_id = {} return unless channels channels.each do |element| channel = Channel.new(element, @bot, self) @channels << channel @channels_by_id[channel.id] = channel end end def process_voice_states(voice_states) return unless voice_states voice_states.each do |element| user_id = element['user_id'].to_i user = @members_by_id[user_id] next unless user user.server_mute = element['mute'] user.server_deaf = element['deaf'] user.self_mute = element['self_mute'] user.self_mute = element['self_mute'] channel_id = element['channel_id'] channel = channel_id ? @channels_by_id[channel_id] : nil user.move(channel) end end def add_role(role) @roles << role end def delete_role(role_id) @roles.reject! { |r| r.id == role_id } @members.each do |user| new_roles = user.roles[@id].reject { |r| r.id == role_id } user.update_roles(self, new_roles) end @channels.each do |channel| overwrites = channel.permission_overwrites.reject { |id, _| id == role_id } channel.update_overwrites(overwrites) end end def add_user(user) @members << user end def delete_user(user_id) @members.reject! { |member| member.id == user_id } end def create_channel(name) response = API.create_channel(@bot.token, @id, name, 'text') Channel.new(JSON.parse(response), @bot) end def create_role response = API.create_role(@bot.token, @id) role = Role.new(JSON.parse(response), @bot) @roles << role role end def ban(user, message_days = 0) API.ban_user(@bot.token, @id, user.id, message_days) end def unban(user) API.unban_user(@bot.token, @id, user.id) end def kick(user) API.kick_user(@bot.token, @id, user.id) end def delete API.delete_server(@bot.token, @id) end alias_method :leave, :delete def name=(name) update_server_data(name: name) end def region=(region) update_server_data(region: region.to_s) end def icon=(icon) update_server_data(icon: icon) end def afk_channel=(afk_channel) update_server_data(afk_channel_id: afk_channel.id) end def afk_channel_id=(afk_channel_id) update_server_data(afk_channel_id: afk_channel_id) end def afk_timeout=(afk_timeout) update_server_data(afk_timeout: afk_timeout) end def update_data(new_data) @name = new_data[:name] || new_data['name'] || @name @region = new_data[:region] || new_data['region'] || @region @icon = new_data[:icon] || new_data['icon'] || @icon @afk_timeout = new_data[:afk_timeout] || new_data['afk_timeout'].to_i || @afk_timeout afk_channel_id = new_data[:afk_channel_id] || new_data['afk_channel_id'].to_i || @afk_channel.id @afk_channel = @bot.channel(afk_channel_id) if afk_channel_id != 0 && (!@afk_channel || afk_channel_id != @afk_channel.id) end private def update_server_data(new_data) API.update_server(@bot.token, @id, new_data[:name] || @name, new_data[:region] || @region, new_data[:icon] || @icon, new_data[:afk_channel_id] || @afk_channel_id, new_data[:afk_timeout] || @afk_timeout) update_data(new_data) end end # A colour (red, green and blue values). Used for role colours class ColourRGB attr_reader :red, :green, :blue, :combined def initialize(combined) @combined = combined @red = (combined >> 16) & 0xFF @green = (combined >> 8) & 0xFF @blue = combined & 0xFF end end ColorRGB = ColourRGB end Parse timestamp as ISO 8601 instead of epoch # These classes hold relevant Discord data, such as messages or channels. require 'ostruct' require 'discordrb/permissions' require 'discordrb/api' require 'discordrb/games' require 'discordrb/events/message' require 'time' require 'base64' # Discordrb module module Discordrb # User on Discord, including internal data like discriminators class User attr_reader :username, :id, :discriminator, :avatar, :voice_channel, :roles attr_accessor :status, :game, :server_mute, :server_deaf, :self_mute, :self_deaf # @roles is a hash of user roles: # Key: Server ID # Value: Array of roles. alias_method :name, :username def initialize(data, bot) @bot = bot @username = data['username'] @id = data['id'].to_i @discriminator = data['discriminator'] @avatar = data['avatar'] @roles = {} @status = :offline end # Utility function to mention users in messages def mention "<@#{@id}>" end # Utility function to send a PM def pm(content = nil) if content # Recursively call pm to get the channel, then send a message to it channel = pm channel.send_message(content) else # If no message was specified, return the PM channel @bot.private_channel(@id) end end # Move a user into a voice channel def move(to_channel) return if to_channel && to_channel.type != 'voice' @voice_channel = to_channel end # Set this user's roles def update_roles(server, roles) @roles[server.id] = roles end # Merge this user's roles with the roles from another instance of this user (from another server) def merge_roles(server, roles) if @roles[server.id] @roles[server.id] = (@roles[server.id] + roles).uniq else @roles[server.id] = roles end end # Delete a specific server from the roles (in case a user leaves a server) def delete_roles(server_id) @roles.delete(server_id) end # Add an await for a message from this user def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { from: @id }.merge(attributes), &block) end # Is the user the bot? def bot? @bot.bot_user.id == @id end # Determine if the user has permission to do an action # action is a permission from Permissions::Flags. # channel is the channel in which the action takes place (not applicable for server-wide actions). def permission?(action, server, channel = nil) # For each role, check if # (1) the channel explicitly allows or permits an action for the role and # (2) if the user is allowed to do the action if the channel doesn't specify return false unless @roles[server.id] @roles[server.id].reduce(false) do |can_act, role| channel_allow = nil if channel && channel.permission_overwrites[role.id] allow = channel.permission_overwrites[role.id].allow deny = channel.permission_overwrites[role.id].deny if allow.instance_variable_get("@#{action}") channel_allow = true elsif deny.instance_variable_get("@#{action}") channel_allow = false end # If the channel has nothing to say on the matter, we can defer to the role itself end if channel_allow == false can_act = false elsif channel_allow == true can_act = true else # channel_allow == nil can_act = role.permissions.instance_variable_get("@#{action}") || can_act end can_act end end # Define methods for querying permissions Discordrb::Permissions::Flags.each_value do |flag| define_method "can_#{flag}?" do |server, channel = nil| permission? flag, server, channel end end end # A class that represents the bot user itself and has methods to change stuff class Profile < User def initialize(data, bot, email, password) super(data, bot) @email = email @password = password end def bot? true end def username=(username) update_server_data(username: username) end def email=(email) update_server_data(email: email) end def password=(password) update_server_data(new_password: password) end def avatar=(avatar) if avatar.is_a? File avatar_string = 'data:image/jpg;base64,' avatar_string += Base64.strict_encode64(avatar.read) update_server_data(avatar: avatar_string) else update_server_data(avatar: avatar) end end def update_data(new_data) @email = new_data[:email] || @email @password = new_data[:new_password] || @password @username = new_data[:username] || @username @avatar = new_data[:avatar] || @avatar end private def update_server_data(new_data) API.update_user(@bot.token, new_data[:email] || @email, @password, new_data[:username] || @username, new_data[:avatar] || @avatar, new_data[:new_password] || nil) update_data(new_data) end end # A Discord role that contains permissions and applies to certain users class Role attr_reader :permissions, :name, :id, :hoist, :colour alias_method :color, :colour # Class that writes data for a Permissions object class RoleWriter def initialize(role, token) @role = role @token = token end def write(bits) @role.send(:packed=, bits, false) end end def initialize(data, bot, server = nil) @bot = bot @server = server @permissions = Permissions.new(data['permissions'], RoleWriter.new(self, @bot.token)) @name = data['name'] @id = data['id'].to_i @hoist = data['hoist'] @colour = ColourRGB.new(data['color']) end def update_from(other) @permissions = other.permissions @name = other.name @hoist = other.hoist @colour = other.colour end def update_data(new_data) @name = new_data[:name] || new_data['name'] || @name @hoist = new_data['hoist'] unless new_data['hoist'].nil? @hoist = new_data[:hoist] unless new_data[:hoist].nil? @colour = new_data[:colour] || (new_data['color'] ? ColourRGB.new(new_data['color']) : @colour) end def name=(name) update_role_data(name: name) end def hoist=(hoist) update_role_data(hoist: hoist) end def colour=(colour) update_role_data(colour: colour) end alias_method :color=, :colour= def packed=(packed, update_perms = true) update_role_data(permissions: packed) @permissions.bits = packed if update_perms end def delete API.delete_role(@bot.token, @server.id, @id) @server.delete_role(@id) end private def update_role_data(new_data) API.update_role(@bot.token, @server.id, @id, new_data[:name] || @name, (new_data[:colour] || @colour).combined, !(!(new_data[:hoist].nil? ? new_data[:hoist] : @hoist)), new_data[:permissions] || @permissions.bits) update_data(new_data) end end # A Discord invite to a channel class Invite attr_reader :channel, :uses, :inviter, :temporary, :revoked, :xkcd, :code alias_method :max_uses, :uses alias_method :user, :inviter alias_method :temporary?, :temporary alias_method :revoked?, :revoked alias_method :xkcd?, :xkcd delegate :server, to: :channel def initialize(data, bot) @bot = bot @channel = Channel.new(data['channel'], bot) @uses = data['uses'] @inviter = @bot.user(data['inviter']['id'].to_i) || User.new(data['inviter'], bot) @temporary = data['temporary'] @revoked = data['revoked'] @xkcd = data['xkcdpass'] @code = data['code'] end def delete API.delete_invite(@bot.token, @code) end end # A Discord channel, including data like the topic class Channel attr_reader :name, :server, :type, :id, :is_private, :recipient, :topic, :position, :permission_overwrites def private? @server.nil? end def initialize(data, bot, server = nil) @bot = bot # data is a sometimes a Hash and othertimes an array of Hashes, you only want the last one if it's an array data = data[-1] if data.is_a?(Array) @id = data['id'].to_i @type = data['type'] || 'text' @topic = data['topic'] @position = data['position'] @is_private = data['is_private'] if @is_private @recipient = User.new(data['recipient'], bot) @name = @recipient.username else @name = data['name'] @server = bot.server(data['guild_id'].to_i) @server ||= server end # Populate permission overwrites @permission_overwrites = {} return unless data['permission_overwrites'] data['permission_overwrites'].each do |element| role_id = element['id'].to_i deny = Permissions.new(element['deny']) allow = Permissions.new(element['allow']) @permission_overwrites[role_id] = OpenStruct.new @permission_overwrites[role_id].deny = deny @permission_overwrites[role_id].allow = allow end end def send_message(content) @bot.send_message(@id, content) end def send_file(file) @bot.send_file(@id, file) end def delete API.delete_channel(@bot.token, @id) end def name=(name) @name = name update_channel_data end def topic=(topic) @topic = topic update_channel_data end def position=(position) @position = position update_channel_data end def update_from(other) @topic = other.topic @name = other.name @is_private = other.is_private @recipient = other.recipient @permission_overwrites = other.permission_overwrites end # List of users currently in a channel def users if @type == 'text' @server.members.select { |u| u.status != :offline } else @server.members.select do |user| user.voice_channel.id == @id if user.voice_channel end end end def history(amount, before_id = nil, after_id = nil) logs = API.channel_log(@bot.token, @id, amount, before_id, after_id) JSON.parse(logs).map { |message| Message.new(message, @bot) } end def update_overwrites(overwrites) @permission_overwrites = overwrites end # Add an await for a message in this channel def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { in: @id }.merge(attributes), &block) end def make_invite(max_age = 0, max_uses = 0, temporary = false, xkcd = false) response = API.create_invite(@bot.token, @id, max_age, max_uses, temporary, xkcd) Invite.new(JSON.parse(response), @bot) end # Starts typing, which displays the typing indicator on the client for five seconds. # If you want to keep typing you'll have to resend this every five seconds. (An abstraction # for this will eventually be coming) def start_typing API.start_typing(@bot.token, @id) end alias_method :send, :send_message alias_method :message, :send_message alias_method :invite, :make_invite private def update_channel_data API.update_channel(@bot.token, @id, @name, @topic, @position) end end # A message on Discord that was sent to a text channel class Message attr_reader :content, :author, :channel, :timestamp, :id, :mentions alias_method :user, :author alias_method :text, :content def initialize(data, bot) @bot = bot @content = data['content'] @author = User.new(data['author'], bot) @channel = bot.channel(data['channel_id'].to_i) @timestamp = Time.parse(data['timestamp']) @id = data['id'].to_i @mentions = [] data['mentions'].each do |element| @mentions << User.new(element, bot) end end def reply(content) @channel.send_message(content) end def edit(new_content) API.edit_message(@bot.token, @channel.id, @id, new_content) end def delete API.delete_message(@bot.token, @channel.id, @id) end # Add an await for a message with the same user and channel def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { from: @author.id, in: @channel.id }.merge(attributes), &block) end def from_bot? @author.bot? end end # A server on Discord class Server attr_reader :region, :name, :owner_id, :id, :members, :channels, :roles, :icon, :afk_timeout, :afk_channel_id def initialize(data, bot) @bot = bot @owner_id = data['owner_id'].to_i @id = data['id'].to_i update_data(data) process_roles(data['roles']) process_members(data['members']) process_presences(data['presences']) process_channels(data['channels']) process_voice_states(data['voice_states']) end def process_roles(roles) # Create roles @roles = [] @roles_by_id = {} roles.each do |element| role = Role.new(element, @bot, self) @roles << role @roles_by_id[role.id] = role end end def process_members(members) @members = [] @members_by_id = {} return unless members members.each do |element| user = User.new(element['user'], @bot) @members << user @members_by_id[user.id] = user user_roles = [] element['roles'].each do |e| role_id = e.to_i user_roles << @roles_by_id[role_id] end user.update_roles(self, user_roles) end end def process_presences(presences) # Update user statuses with presence info return unless presences presences.each do |element| next unless element['user'] user_id = element['user']['id'].to_i user = @members_by_id[user_id] if user user.status = element['status'].to_sym user.game = Discordrb::Games.find_game(element['game_id']) end end end def process_channels(channels) @channels = [] @channels_by_id = {} return unless channels channels.each do |element| channel = Channel.new(element, @bot, self) @channels << channel @channels_by_id[channel.id] = channel end end def process_voice_states(voice_states) return unless voice_states voice_states.each do |element| user_id = element['user_id'].to_i user = @members_by_id[user_id] next unless user user.server_mute = element['mute'] user.server_deaf = element['deaf'] user.self_mute = element['self_mute'] user.self_mute = element['self_mute'] channel_id = element['channel_id'] channel = channel_id ? @channels_by_id[channel_id] : nil user.move(channel) end end def add_role(role) @roles << role end def delete_role(role_id) @roles.reject! { |r| r.id == role_id } @members.each do |user| new_roles = user.roles[@id].reject { |r| r.id == role_id } user.update_roles(self, new_roles) end @channels.each do |channel| overwrites = channel.permission_overwrites.reject { |id, _| id == role_id } channel.update_overwrites(overwrites) end end def add_user(user) @members << user end def delete_user(user_id) @members.reject! { |member| member.id == user_id } end def create_channel(name) response = API.create_channel(@bot.token, @id, name, 'text') Channel.new(JSON.parse(response), @bot) end def create_role response = API.create_role(@bot.token, @id) role = Role.new(JSON.parse(response), @bot) @roles << role role end def ban(user, message_days = 0) API.ban_user(@bot.token, @id, user.id, message_days) end def unban(user) API.unban_user(@bot.token, @id, user.id) end def kick(user) API.kick_user(@bot.token, @id, user.id) end def delete API.delete_server(@bot.token, @id) end alias_method :leave, :delete def name=(name) update_server_data(name: name) end def region=(region) update_server_data(region: region.to_s) end def icon=(icon) update_server_data(icon: icon) end def afk_channel=(afk_channel) update_server_data(afk_channel_id: afk_channel.id) end def afk_channel_id=(afk_channel_id) update_server_data(afk_channel_id: afk_channel_id) end def afk_timeout=(afk_timeout) update_server_data(afk_timeout: afk_timeout) end def update_data(new_data) @name = new_data[:name] || new_data['name'] || @name @region = new_data[:region] || new_data['region'] || @region @icon = new_data[:icon] || new_data['icon'] || @icon @afk_timeout = new_data[:afk_timeout] || new_data['afk_timeout'].to_i || @afk_timeout afk_channel_id = new_data[:afk_channel_id] || new_data['afk_channel_id'].to_i || @afk_channel.id @afk_channel = @bot.channel(afk_channel_id) if afk_channel_id != 0 && (!@afk_channel || afk_channel_id != @afk_channel.id) end private def update_server_data(new_data) API.update_server(@bot.token, @id, new_data[:name] || @name, new_data[:region] || @region, new_data[:icon] || @icon, new_data[:afk_channel_id] || @afk_channel_id, new_data[:afk_timeout] || @afk_timeout) update_data(new_data) end end # A colour (red, green and blue values). Used for role colours class ColourRGB attr_reader :red, :green, :blue, :combined def initialize(combined) @combined = combined @red = (combined >> 16) & 0xFF @green = (combined >> 8) & 0xFF @blue = combined & 0xFF end end ColorRGB = ColourRGB end
# frozen_string_literal: true # These classes hold relevant Discord data, such as messages or channels. require 'ostruct' require 'discordrb/permissions' require 'discordrb/errors' require 'discordrb/api' require 'discordrb/api/channel' require 'discordrb/api/server' require 'discordrb/api/invite' require 'discordrb/api/user' require 'discordrb/webhooks/embeds' require 'time' require 'base64' # Discordrb module module Discordrb # The unix timestamp Discord IDs are based on DISCORD_EPOCH = 1_420_070_400_000 # Compares two objects based on IDs - either the objects' IDs are equal, or one object is equal to the other's ID. def self.id_compare(one_id, other) other.respond_to?(:resolve_id) ? (one_id.resolve_id == other.resolve_id) : (one_id == other) end # The maximum length a Discord message can have CHARACTER_LIMIT = 2000 # Splits a message into chunks of 2000 characters. Attempts to split by lines if possible. # @param msg [String] The message to split. # @return [Array<String>] the message split into chunks def self.split_message(msg) # If the messages is empty, return an empty array return [] if msg.empty? # Split the message into lines lines = msg.lines # Turn the message into a "triangle" of consecutively longer slices, for example the array [1,2,3,4] would become # [ # [1], # [1, 2], # [1, 2, 3], # [1, 2, 3, 4] # ] tri = [*0..(lines.length - 1)].map { |i| lines.combination(i + 1).first } # Join the individual elements together to get an array of strings with consecutively more lines joined = tri.map(&:join) # Find the largest element that is still below the character limit, or if none such element exists return the first ideal = joined.max_by { |e| e.length > CHARACTER_LIMIT ? -1 : e.length } # If it's still larger than the character limit (none was smaller than it) split it into slices with the length # being the character limit, otherwise just return an array with one element ideal_ary = ideal.length > CHARACTER_LIMIT ? ideal.chars.each_slice(CHARACTER_LIMIT).map(&:join) : [ideal] # Slice off the ideal part and strip newlines rest = msg[ideal.length..-1].strip # If none remains, return an empty array -> we're done return [] unless rest # Otherwise, call the method recursively to split the rest of the string and add it onto the ideal array ideal_ary + split_message(rest) end # Mixin for objects that have IDs module IDObject # @return [Integer] the ID which uniquely identifies this object across Discord. attr_reader :id alias_method :resolve_id, :id # ID based comparison def ==(other) Discordrb.id_compare(@id, other) end # Estimates the time this object was generated on based on the beginning of the ID. This is fairly accurate but # shouldn't be relied on as Discord might change its algorithm at any time # @return [Time] when this object was created at def creation_time # Milliseconds ms = (@id >> 22) + DISCORD_EPOCH Time.at(ms / 1000.0) end # Creates an artificial snowflake at the given point in time. Useful for comparing against. # @param time [Time] The time the snowflake should represent. # @return [Integer] a snowflake with the timestamp data as the given time def self.synthesise(time) ms = (time.to_f * 1000).to_i (ms - DISCORD_EPOCH) << 22 end class << self alias_method :synthesize, :synthesise end end # Mixin for the attributes users should have module UserAttributes # @return [String] this user's username attr_reader :username alias_method :name, :username # @return [String] this user's discriminator which is used internally to identify users with identical usernames. attr_reader :discriminator alias_method :discrim, :discriminator alias_method :tag, :discriminator alias_method :discord_tag, :discriminator # @return [true, false] whether this user is a Discord bot account attr_reader :bot_account alias_method :bot_account?, :bot_account # @return [String] the ID of this user's current avatar, can be used to generate an avatar URL. # @see #avatar_url attr_accessor :avatar_id # Utility function to mention users in messages # @return [String] the mention code in the form of <@id> def mention "<@#{@id}>" end # Utility function to get Discord's distinct representation of a user, i. e. username + discriminator # @return [String] distinct representation of user def distinct "#{@username}##{@discriminator}" end # Utility function to get a user's avatar URL. # @return [String] the URL to the avatar image. def avatar_url API::User.avatar_url(@id, @avatar_id) end end # User on Discord, including internal data like discriminators class User include IDObject include UserAttributes # @return [Symbol] the current online status of the user (`:online`, `:offline` or `:idle`) attr_reader :status # @return [String, nil] the game the user is currently playing, or `nil` if none is being played. attr_reader :game # @return [String, nil] the URL to the stream, if the user is currently streaming something. attr_reader :stream_url # @return [String, Integer, nil] the type of the stream. Can technically be set to anything, most of the time it # will be 0 for no stream or 1 for Twitch streams. attr_reader :stream_type def initialize(data, bot) @bot = bot @username = data['username'] @id = data['id'].to_i @discriminator = data['discriminator'] @avatar_id = data['avatar'] @roles = {} @bot_account = false @bot_account = true if data['bot'] @status = :offline end # Get a user's PM channel or send them a PM # @overload pm # Creates a private message channel for this user or returns an existing one if it already exists # @return [Channel] the PM channel to this user. # @overload pm(content) # Sends a private to this user. # @param content [String] The content to send. # @return [Message] the message sent to this user. def pm(content = nil) if content # Recursively call pm to get the channel, then send a message to it channel = pm channel.send_message(content) else # If no message was specified, return the PM channel @bot.pm_channel(@id) end end alias_method :dm, :pm # Send the user a file. # @param file [File] The file to send to the user # @param caption [String] The caption of the file being sent # @return [Message] the message sent to this user. def send_file(file, caption = nil) pm.send_file(file, caption: caption) end # Set the user's name # @note for internal use only # @!visibility private def update_username(username) @username = username end # Set the user's presence data # @note for internal use only # @!visibility private def update_presence(data) @status = data['status'].to_sym if data['game'] game = data['game'] @game = game['name'] @stream_url = game['url'] @stream_type = game['type'] else @game = @stream_url = @stream_type = nil end end # Add an await for a message from this user. Specifically, this adds a global await for a MessageEvent with this # user's ID as a :from attribute. # @see Bot#add_await def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { from: @id }.merge(attributes), &block) end # Gets the member this user is on a server # @param server [Server] The server to get the member for # @return [Member] this user as a member on a particular server def on(server) id = server.resolve_id @bot.server(id).member(@id) end # Is the user the bot? # @return [true, false] whether this user is the bot def current_bot? @bot.profile.id == @id end # @return [true, false] whether this user is a fake user for a webhook message def webhook? @discriminator == Message::ZERO_DISCRIM end [:offline, :idle, :online].each do |e| define_method(e.to_s + '?') do @status.to_sym == e end end # The inspect method is overwritten to give more useful output def inspect "<User username=#{@username} id=#{@id} discriminator=#{@discriminator}>" end end # OAuth Application information class Application include IDObject # @return [String] the application name attr_reader :name # @return [String] the application description attr_reader :description # @return [Array<String>] the applications origins permitted to use RPC attr_reader :rpc_origins # @return [Integer] attr_reader :flags # Gets the user object of the owner. May be limited to username, discriminator, # ID and avatar if the bot cannot reach the owner. # @return [User] the user object of the owner attr_reader :owner def initialize(data, bot) @bot = bot @name = data['name'] @id = data['id'].to_i @description = data['description'] @icon_id = data['icon'] @rpc_origins = data['rpc_origins'] @flags = data['flags'] @owner = @bot.ensure_user(data['owner']) end # Utility function to get a application's icon URL. # @return [String, nil] the URL to the icon image (nil if no image is set). def icon_url return nil if @icon_id.nil? API.app_icon_url(@id, @icon_id) end # The inspect method is overwritten to give more useful output def inspect "<Application name=#{@name} id=#{@id}>" end end # Mixin for the attributes members and private members should have module MemberAttributes # @return [Time] when this member joined the server. attr_reader :joined_at # @return [String, nil] the nickname this member has, or nil if it has none. attr_reader :nick alias_method :nickname, :nick # @return [Array<Role>] the roles this member has. attr_reader :roles # @return [Server] the server this member is on. attr_reader :server end # Mixin to calculate resulting permissions from overrides etc. module PermissionCalculator # Checks whether this user can do the particular action, regardless of whether it has the permission defined, # through for example being the server owner or having the Manage Roles permission # @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list. # @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked. # @example Check if the bot can send messages to a specific channel in a server. # bot_profile = bot.profile.on(event.server) # can_send_messages = bot_profile.permission?(:send_messages, channel) # @return [true, false] whether or not this user has the permission. def permission?(action, channel = nil) # If the member is the server owner, it irrevocably has all permissions. return true if owner? # First, check whether the user has Manage Roles defined. # (Coincidentally, Manage Permissions is the same permission as Manage Roles, and a # Manage Permissions deny overwrite will override Manage Roles, so we can just check for # Manage Roles once and call it a day.) return true if defined_permission?(:administrator, channel) # Otherwise, defer to defined_permission defined_permission?(action, channel) end # Checks whether this user has a particular permission defined (i. e. not implicit, through for example # Manage Roles) # @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list. # @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked. # @example Check if a member has the Manage Channels permission defined in the server. # has_manage_channels = member.defined_permission?(:manage_channels) # @return [true, false] whether or not this user has the permission defined. def defined_permission?(action, channel = nil) # Get the permission the user's roles have role_permission = defined_role_permission?(action, channel) # Once we have checked the role permission, we have to check the channel overrides for the # specific user user_specific_override = permission_overwrite(action, channel, id) # Use the ID reader as members have no ID instance variable # Merge the two permissions - if an override is defined, it has to be allow, otherwise we only care about the role return role_permission unless user_specific_override user_specific_override == :allow end # Define methods for querying permissions Discordrb::Permissions::Flags.each_value do |flag| define_method "can_#{flag}?" do |channel = nil| permission? flag, channel end end alias_method :can_administrate?, :can_administrator? private def defined_role_permission?(action, channel) # For each role, check if # (1) the channel explicitly allows or permits an action for the role and # (2) if the user is allowed to do the action if the channel doesn't specify @roles.reduce(false) do |can_act, role| # Get the override defined for the role on the channel channel_allow = permission_overwrite(action, channel, role.id) can_act = if channel_allow # If the channel has an override, check whether it is an allow - if yes, # the user can act, if not, it can't channel_allow == :allow else # Otherwise defer to the role role.permissions.instance_variable_get("@#{action}") || can_act end can_act end end def permission_overwrite(action, channel, id) # If no overwrites are defined, or no channel is set, no overwrite will be present return nil unless channel && channel.permission_overwrites[id] # Otherwise, check the allow and deny objects allow = channel.permission_overwrites[id].allow deny = channel.permission_overwrites[id].deny if allow.instance_variable_get("@#{action}") :allow elsif deny.instance_variable_get("@#{action}") :deny end # If there's no variable defined, nil will implicitly be returned end end # A voice state represents the state of a member's connection to a voice channel. It includes data like the voice # channel the member is connected to and mute/deaf flags. class VoiceState # @return [Integer] the ID of the user whose voice state is represented by this object. attr_reader :user_id # @return [true, false] whether this voice state's member is muted server-wide. attr_reader :mute # @return [true, false] whether this voice state's member is deafened server-wide. attr_reader :deaf # @return [true, false] whether this voice state's member has muted themselves. attr_reader :self_mute # @return [true, false] whether this voice state's member has deafened themselves. attr_reader :self_deaf # @return [Channel] the voice channel this voice state's member is in. attr_reader :voice_channel # @!visibility private def initialize(user_id) @user_id = user_id end # Update this voice state with new data from Discord # @note For internal use only. # @!visibility private def update(channel, mute, deaf, self_mute, self_deaf) @voice_channel = channel @mute = mute @deaf = deaf @self_mute = self_mute @self_deaf = self_deaf end end # A presence represents a # A member is a user on a server. It differs from regular users in that it has roles, voice statuses and things like # that. class Member < DelegateClass(User) # @return [true, false] whether this member is muted server-wide. def mute voice_state_attribute(:mute) end # @return [true, false] whether this member is deafened server-wide. def deaf voice_state_attribute(:deaf) end # @return [true, false] whether this member has muted themselves. def self_mute voice_state_attribute(:self_mute) end # @return [true, false] whether this member has deafened themselves. def self_deaf voice_state_attribute(:self_deaf) end # @return [Channel] the voice channel this member is in. def voice_channel voice_state_attribute(:voice_channel) end alias_method :muted?, :mute alias_method :deafened?, :deaf alias_method :self_muted?, :self_mute alias_method :self_deafened?, :self_deaf include MemberAttributes # @!visibility private def initialize(data, server, bot) @bot = bot @user = bot.ensure_user(data['user']) super @user # Initialize the delegate class # Somehow, Discord doesn't send the server ID in the standard member format... raise ArgumentError, 'Cannot create a member without any information about the server!' if server.nil? && data['guild_id'].nil? @server = server || bot.server(data['guild_id'].to_i) # Initialize the roles by getting the roles from the server one-by-one update_roles(data['roles']) @nick = data['nick'] @joined_at = data['joined_at'] ? Time.parse(data['joined_at']) : nil end # @return [true, false] whether this member is the server owner. def owner? @server.owner == self end # @param role [Role, Integer, #resolve_id] the role to check or its ID. # @return [true, false] whether this member has the specified role. def role?(role) role = role.resolve_id @roles.any? { |e| e.id == role } end # Bulk sets a member's roles. # @param role [Role, Array<Role>] The role(s) to set. def roles=(role) role_ids = role_id_array(role) API::Server.update_member(@bot.token, @server.id, @user.id, roles: role_ids) end # Adds and removes roles from a member. # @param add [Role, Array<Role>] The role(s) to add. # @param remove [Role, Array<Role>] The role(s) to remove. # @example Remove the 'Member' role from a user, and add the 'Muted' role to them. # to_add = server.roles.find {|role| role.name == 'Muted'} # to_remove = server.roles.find {|role| role.name == 'Member'} # member.modify_roles(to_add, to_remove) def modify_roles(add, remove) add_role_ids = role_id_array(add) remove_role_ids = role_id_array(remove) old_role_ids = @roles.map(&:id) new_role_ids = (old_role_ids - remove_role_ids + add_role_ids).uniq API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids) end # Adds one or more roles to this member. # @param role [Role, Array<Role>] The role(s) to add. def add_role(role) role_ids = role_id_array(role) old_role_ids = @roles.map(&:id) new_role_ids = (old_role_ids + role_ids).uniq API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids) end # Removes one or more roles from this member. # @param role [Role, Array<Role>] The role(s) to remove. def remove_role(role) old_role_ids = @roles.map(&:id) role_ids = role_id_array(role) new_role_ids = old_role_ids.reject { |i| role_ids.include?(i) } API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids) end # Server deafens this member. def server_deafen API::Server.update_member(@bot.token, @server.id, @user.id, deaf: true) end # Server undeafens this member. def server_undeafen API::Server.update_member(@bot.token, @server.id, @user.id, deaf: false) end # Server mutes this member. def server_mute API::Server.update_member(@bot.token, @server.id, @user.id, mute: true) end # Server unmutes this member. def server_unmute API::Server.update_member(@bot.token, @server.id, @user.id, mute: false) end # Sets or resets this member's nickname. Requires the Change Nickname permission for the bot itself and Manage # Nicknames for other users. # @param nick [String, nil] The string to set the nickname to, or nil if it should be reset. def nick=(nick) # Discord uses the empty string to signify 'no nickname' so we convert nil into that nick ||= '' if @user.current_bot? API::User.change_own_nickname(@bot.token, @server.id, nick) else API::Server.update_member(@bot.token, @server.id, @user.id, nick: nick) end end alias_method :nickname=, :nick= # @return [String] the name the user displays as (nickname if they have one, username otherwise) def display_name nickname || username end # Update this member's roles # @note For internal use only. # @!visibility private def update_roles(roles) @roles = roles.map do |role| role.is_a?(Role) ? role : @server.role(role.to_i) end end # Update this member's nick # @note For internal use only. # @!visibility private def update_nick(nick) @nick = nick end include PermissionCalculator # Overwriting inspect for debug purposes def inspect "<Member user=#{@user.inspect} server=#{@server.inspect} joined_at=#{@joined_at} roles=#{@roles.inspect} voice_channel=#{@voice_channel.inspect} mute=#{@mute} deaf=#{@deaf} self_mute=#{@self_mute} self_deaf=#{@self_deaf}>" end private # Utility method to get a list of role IDs from one role or an array of roles def role_id_array(role) if role.is_a? Array role.map(&:resolve_id) else [role.resolve_id] end end # Utility method to get data out of this member's voice state def voice_state_attribute(name) voice_state = @server.voice_states[@user.id] voice_state.send name if voice_state end end # Recipients are members on private channels - they exist for completeness purposes, but all # the attributes will be empty. class Recipient < DelegateClass(User) include MemberAttributes # @return [Channel] the private channel this recipient is the recipient of. attr_reader :channel # @!visibility private def initialize(user, channel, bot) @bot = bot @channel = channel raise ArgumentError, 'Tried to create a recipient for a public channel!' unless @channel.private? @user = user super @user # Member attributes @mute = @deaf = @self_mute = @self_deaf = false @voice_channel = nil @server = nil @roles = [] @joined_at = @channel.creation_time end # Overwriting inspect for debug purposes def inspect "<Recipient user=#{@user.inspect} channel=#{@channel.inspect}>" end end # This class is a special variant of User that represents the bot's user profile (things like own username and the avatar). # It can be accessed using {Bot#profile}. class Profile < User def initialize(data, bot) super(data, bot) end # Whether or not the user is the bot. The Profile can only ever be the bot user, so this always returns true. # @return [true] def current_bot? true end # Sets the bot's username. # @param username [String] The new username. def username=(username) update_profile_data(username: username) end alias_method :name=, :username= # Changes the bot's avatar. # @param avatar [String, #read] A JPG file to be used as the avatar, either # something readable (e. g. File Object) or as a data URL. def avatar=(avatar) if avatar.respond_to? :read # Set the file to binary mode if supported, so we don't get problems with Windows avatar.binmode if avatar.respond_to?(:binmode) avatar_string = 'data:image/jpg;base64,' avatar_string += Base64.strict_encode64(avatar.read) update_profile_data(avatar: avatar_string) else update_profile_data(avatar: avatar) end end # Updates the cached profile data with the new one. # @note For internal use only. # @!visibility private def update_data(new_data) @username = new_data[:username] || @username @avatar_id = new_data[:avatar_id] || @avatar_id end # Sets the user status setting to Online. # @note Only usable on User accounts. def online update_profile_status_setting('online') end # Sets the user status setting to Idle. # @note Only usable on User accounts. def idle update_profile_status_setting('idle') end # Sets the user status setting to Do Not Disturb. # @note Only usable on User accounts. def dnd update_profile_status_setting('dnd') end alias_method(:busy, :dnd) # Sets the user status setting to Invisible. # @note Only usable on User accounts. def invisible update_profile_status_setting('invisible') end # The inspect method is overwritten to give more useful output def inspect "<Profile user=#{super}>" end private # Internal handler for updating the user's status setting def update_profile_status_setting(status) API::User.change_status_setting(@bot.token, status) end def update_profile_data(new_data) API::User.update_profile(@bot.token, nil, nil, new_data[:username] || @username, new_data.key?(:avatar) ? new_data[:avatar] : @avatar_id) update_data(new_data) end end # A Discord role that contains permissions and applies to certain users class Role include IDObject # @return [Permissions] this role's permissions. attr_reader :permissions # @return [String] this role's name ("new role" if it hasn't been changed) attr_reader :name # @return [true, false] whether or not this role should be displayed separately from other users attr_reader :hoist # @return [true, false] whether this role can be mentioned using a role mention attr_reader :mentionable alias_method :mentionable?, :mentionable # @return [ColourRGB] the role colour attr_reader :colour alias_method :color, :colour # @return [Integer] the position of this role in the hierarchy attr_reader :position # This class is used internally as a wrapper to a Role object that allows easy writing of permission data. class RoleWriter # @!visibility private def initialize(role, token) @role = role @token = token end # Write the specified permission data to the role, without updating the permission cache # @param bits [Integer] The packed permissions to write. def write(bits) @role.send(:packed=, bits, false) end # The inspect method is overridden, in this case to prevent the token being leaked def inspect "<RoleWriter role=#{@role} token=...>" end end # @!visibility private def initialize(data, bot, server = nil) @bot = bot @server = server @permissions = Permissions.new(data['permissions'], RoleWriter.new(self, @bot.token)) @name = data['name'] @id = data['id'].to_i @position = data['position'] @hoist = data['hoist'] @mentionable = data['mentionable'] @colour = ColourRGB.new(data['color']) end # @return [String] a string that will mention this role, if it is mentionable. def mention "<@&#{@id}>" end # @return [Array<Member>] an array of members who have this role. # @note This requests a member chunk if it hasn't for the server before, which may be slow initially def members @server.members.select { |m| m.role? role } end alias_method :users, :members # Updates the data cache from another Role object # @note For internal use only # @!visibility private def update_from(other) @permissions = other.permissions @name = other.name @hoist = other.hoist @colour = other.colour @position = other.position end # Updates the data cache from a hash containing data # @note For internal use only # @!visibility private def update_data(new_data) @name = new_data[:name] || new_data['name'] || @name @hoist = new_data['hoist'] unless new_data['hoist'].nil? @hoist = new_data[:hoist] unless new_data[:hoist].nil? @colour = new_data[:colour] || (new_data['color'] ? ColourRGB.new(new_data['color']) : @colour) end # Sets the role name to something new # @param name [String] The name that should be set def name=(name) update_role_data(name: name) end # Changes whether or not this role is displayed at the top of the user list # @param hoist [true, false] The value it should be changed to def hoist=(hoist) update_role_data(hoist: hoist) end # Changes whether or not this role can be mentioned # @param mentionable [true, false] The value it should be changed to def mentionable=(mentionable) update_role_data(mentionable: mentionable) end # Sets the role colour to something new # @param colour [ColourRGB] The new colour def colour=(colour) update_role_data(colour: colour) end alias_method :color=, :colour= # Changes this role's permissions to a fixed bitfield. This allows setting multiple permissions at once with just # one API call. # # Information on how this bitfield is structured can be found at # https://discordapp.com/developers/docs/topics/permissions. # @example Remove all permissions from a role # role.packed = 0 # @param packed [Integer] A bitfield with the desired permissions value. # @param update_perms [true, false] Whether the internal data should also be updated. This should always be true # when calling externally. def packed=(packed, update_perms = true) update_role_data(permissions: packed) @permissions.bits = packed if update_perms end # Deletes this role. This cannot be undone without recreating the role! def delete API::Server.delete_role(@bot.token, @server.id, @id) @server.delete_role(@id) end # The inspect method is overwritten to give more useful output def inspect "<Role name=#{@name} permissions=#{@permissions.inspect} hoist=#{@hoist} colour=#{@colour.inspect} server=#{@server.inspect}>" end private def update_role_data(new_data) API::Server.update_role(@bot.token, @server.id, @id, new_data[:name] || @name, (new_data[:colour] || @colour).combined, new_data[:hoist].nil? ? @hoist : new_data[:hoist], new_data[:mentionable].nil? ? @mentionable : new_data[:mentionable], new_data[:permissions] || @permissions.bits) update_data(new_data) end end # A channel referenced by an invite. It has less data than regular channels, so it's a separate class class InviteChannel include IDObject # @return [String] this channel's name. attr_reader :name # @return [Integer] this channel's type (0: text, 1: private, 2: voice, 3: group). attr_reader :type # @!visibility private def initialize(data, bot) @bot = bot @id = data['id'].to_i @name = data['name'] @type = data['type'] end end # A server referenced to by an invite class InviteServer include IDObject # @return [String] this server's name. attr_reader :name # @return [String, nil] the hash of the server's invite splash screen (for partnered servers) or nil if none is # present attr_reader :splash_hash # @!visibility private def initialize(data, bot) @bot = bot @id = data['id'].to_i @name = data['name'] @splash_hash = data['splash_hash'] end end # A Discord invite to a channel class Invite # @return [InviteChannel] the channel this invite references. attr_reader :channel # @return [InviteServer] the server this invite references. attr_reader :server # @return [Integer] the amount of uses left on this invite. attr_reader :uses alias_method :max_uses, :uses # @return [User, nil] the user that made this invite. May also be nil if the user can't be determined. attr_reader :inviter alias_method :user, :inviter # @return [true, false] whether or not this invite is temporary. attr_reader :temporary alias_method :temporary?, :temporary # @return [true, false] whether this invite is still valid. attr_reader :revoked alias_method :revoked?, :revoked # @return [String] this invite's code attr_reader :code # @!visibility private def initialize(data, bot) @bot = bot @channel = InviteChannel.new(data['channel'], bot) @server = InviteServer.new(data['guild'], bot) @uses = data['uses'] @inviter = data['inviter'] ? (@bot.user(data['inviter']['id'].to_i) || User.new(data['inviter'], bot)) : nil @temporary = data['temporary'] @revoked = data['revoked'] @code = data['code'] end # Code based comparison def ==(other) other.respond_to?(:code) ? (@code == other.code) : (@code == other) end # Deletes this invite def delete API::Invite.delete(@bot.token, @code) end alias_method :revoke, :delete # The inspect method is overwritten to give more useful output def inspect "<Invite code=#{@code} channel=#{@channel} uses=#{@uses} temporary=#{@temporary} revoked=#{@revoked}>" end # Creates an invite URL. def url "https://discord.gg/#{@code}" end end # A Discord channel, including data like the topic class Channel include IDObject # @return [String] this channel's name. attr_reader :name # @return [Server, nil] the server this channel is on. If this channel is a PM channel, it will be nil. attr_reader :server # @return [Integer] the type of this channel (0: text, 1: private, 2: voice, 3: group) attr_reader :type # @return [Integer, nil] the id of the owner of the group channel or nil if this is not a group channel. attr_reader :owner_id # @return [Array<Recipient>, nil] the array of recipients of the private messages, or nil if this is not a Private channel attr_reader :recipients # @return [String] the channel's topic attr_reader :topic # @return [Integer] the bitrate (in bps) of the channel attr_reader :bitrate # @return [Integer] the amount of users that can be in the channel. `0` means it is unlimited. attr_reader :user_limit alias_method :limit, :user_limit # @return [Integer] the channel's position on the channel list attr_reader :position # This channel's permission overwrites, represented as a hash of role/user ID to an OpenStruct which has the # `allow` and `deny` properties which are {Permissions} objects respectively. # @return [Hash<Integer => OpenStruct>] the channel's permission overwrites attr_reader :permission_overwrites alias_method :overwrites, :permission_overwrites # @return [true, false] whether or not this channel is a PM or group channel. def private? pm? || group? end # @return [String] a string that will mention the channel as a clickable link on Discord. def mention "<##{@id}>" end # @return [Recipient, nil] the recipient of the private messages, or nil if this is not a PM channel def recipient @recipients.first if pm? end # @!visibility private def initialize(data, bot, server = nil) @bot = bot # data is a sometimes a Hash and other times an array of Hashes, you only want the last one if it's an array data = data[-1] if data.is_a?(Array) @id = data['id'].to_i @type = data['type'] || 0 @topic = data['topic'] @bitrate = data['bitrate'] @user_limit = data['user_limit'] @position = data['position'] if private? @recipients = [] if data['recipients'] data['recipients'].each do |recipient| recipient_user = bot.ensure_user(recipient) @recipients << Recipient.new(recipient_user, self, bot) end end if pm? @name = @recipients.first.username else @name = data['name'] @owner_id = data['owner_id'] end else @name = data['name'] @server = if server server else bot.server(data['guild_id'].to_i) end end # Populate permission overwrites @permission_overwrites = {} return unless data['permission_overwrites'] data['permission_overwrites'].each do |element| role_id = element['id'].to_i deny = Permissions.new(element['deny']) allow = Permissions.new(element['allow']) @permission_overwrites[role_id] = OpenStruct.new @permission_overwrites[role_id].deny = deny @permission_overwrites[role_id].allow = allow end end # @return [true, false] whether or not this channel is a text channel def text? @type.zero? end # @return [true, false] whether or not this channel is a PM channel. def pm? @type == 1 end # @return [true, false] whether or not this channel is a voice channel. def voice? @type == 2 end # @return [true, false] whether or not this channel is a group channel. def group? @type == 3 end # Sends a message to this channel. # @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error. # @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech. # @param embed [Hash, Discordrb::Webhooks::Embed, nil] The rich embed to append to this message. # @return [Message] the message that was sent. def send_message(content, tts = false, embed = nil) @bot.send_message(@id, content, tts, embed) end alias_method :send, :send_message # Sends a temporary message to this channel. # @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error. # @param timeout [Float] The amount of time in seconds after which the message sent will be deleted. # @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech. # @param embed [Hash, Discordrb::Webhooks::Embed, nil] The rich embed to append to this message. def send_temporary_message(content, timeout, tts = false, embed = nil) @bot.send_temporary_message(@id, content, timeout, tts, embed) end # Convenience method to send a message with an embed. # @example Send a message with an embed # channel.send_embed do |embed| # embed.title = 'The Ruby logo' # embed.image = Discordrb::Webhooks::EmbedImage.new(url: 'https://www.ruby-lang.org/images/header-ruby-logo.png') # end # @param message [String] The message that should be sent along with the embed. If this is the empty string, only the embed will be shown. # @param embed [Discordrb::Webhooks::Embed, nil] The embed to start the building process with, or nil if one should be created anew. # @yield [embed] Yields the embed to allow for easy building inside a block. # @yieldparam embed [Discordrb::Webhooks::Embed] The embed from the parameters, or a new one. # @return [Message] The resulting message. def send_embed(message = '', embed = nil) embed ||= Discordrb::Webhooks::Embed.new yield(embed) if block_given? send_message(message, false, embed) end # Sends multiple messages to a channel # @param content [Array<String>] The messages to send. def send_multiple(content) content.each { |e| send_message(e) } end # Splits a message into chunks whose length is at most the Discord character limit, then sends them individually. # Useful for sending long messages, but be wary of rate limits! def split_send(content) send_multiple(Discordrb.split_message(content)) end # Sends a file to this channel. If it is an image, it will be embedded. # @param file [File] The file to send. There's no clear size limit for this, you'll have to attempt it for yourself (most non-image files are fine, large images may fail to embed) # @param caption [string] The caption for the file. # @param tts [true, false] Whether or not this file's caption should be sent using Discord text-to-speech. def send_file(file, caption: nil, tts: false) @bot.send_file(@id, file, caption: caption, tts: tts) end # Deletes a message on this channel. Mostly useful in case a message needs to be deleted when only the ID is known # @param message [Message, String, Integer, #resolve_id] The message that should be deleted. def delete_message(message) API::Channel.delete_message(@bot.token, @id, message.resolve_id) end # Permanently deletes this channel def delete API::Channel.delete(@bot.token, @id) end # Sets this channel's name. The name must be alphanumeric with dashes, unless this is a voice channel (then there are no limitations) # @param name [String] The new name. def name=(name) @name = name update_channel_data end # Sets this channel's topic. # @param topic [String] The new topic. def topic=(topic) raise 'Tried to set topic on voice channel' if voice? @topic = topic update_channel_data end # Sets this channel's bitrate. # @param bitrate [Integer] The new bitrate (in bps). Number has to be between 8000-96000 (128000 for VIP servers) def bitrate=(bitrate) raise 'Tried to set bitrate on text channel' if text? @bitrate = bitrate update_channel_data end # Sets this channel's user limit. # @param limit [Integer] The new user limit. `0` for unlimited, has to be a number between 0-99 def user_limit=(limit) raise 'Tried to set user_limit on text channel' if text? @user_limit = limit update_channel_data end alias_method :limit=, :user_limit= # Sets this channel's position in the list. # @param position [Integer] The new position. def position=(position) @position = position update_channel_data end # Defines a permission overwrite for this channel that sets the specified thing to the specified allow and deny # permission sets, or change an existing one. # @param thing [User, Role] What to define an overwrite for. # @param allow [#bits, Permissions, Integer] The permission sets that should receive an `allow` override (i. e. a # green checkmark on Discord) # @param deny [#bits, Permissions, Integer] The permission sets that should receive a `deny` override (i. e. a red # cross on Discord) # @example Define a permission overwrite for a user that can then mention everyone and use TTS, but not create any invites # allow = Discordrb::Permissions.new # allow.can_mention_everyone = true # allow.can_send_tts_messages = true # # deny = Discordrb::Permissions.new # deny.can_create_instant_invite = true # # channel.define_overwrite(user, allow, deny) def define_overwrite(thing, allow, deny) allow_bits = allow.respond_to?(:bits) ? allow.bits : allow deny_bits = deny.respond_to?(:bits) ? deny.bits : deny type = if thing.is_a?(User) || thing.is_a?(Member) || thing.is_a?(Recipient) || thing.is_a?(Profile) :member elsif thing.is_a? Role :role else raise ArgumentError, '`thing` in define_overwrite needs to be a kind of User (User, Member, Recipient, Profile) or a Role!' end API::Channel.update_permission(@bot.token, @id, thing.id, allow_bits, deny_bits, type) end # Deletes a permission overwrite for this channel # @param target [Member, User, Role, Profile, Recipient, #resolve_id] What permission overwrite to delete def delete_overwrite(target) raise 'Tried deleting a overwrite for an invalid target' unless target.is_a?(Member) || target.is_a?(User) || target.is_a?(Role) || target.is_a?(Profile) || target.is_a?(Recipient) || target.respond_to?(:resolve_id) API::Channel.delete_permission(@bot.token, @id, target.resolve_id) end # Updates the cached data from another channel. # @note For internal use only # @!visibility private def update_from(other) @topic = other.topic @name = other.name @position = other.position @topic = other.topic @recipients = other.recipients @bitrate = other.bitrate @user_limit = other.user_limit @permission_overwrites = other.permission_overwrites end # The list of users currently in this channel. For a voice channel, it will return all the members currently # in that channel. For a text channel, it will return all online members that have permission to read it. # @return [Array<Member>] the users in this channel def users if text? @server.online_members(include_idle: true).select { |u| u.can_read_messages? self } elsif voice? @server.voice_states.map { |id, voice_state| @server.member(id) if !voice_state.voice_channel.nil? && voice_state.voice_channel.id == @id }.compact end end # Retrieves some of this channel's message history. # @param amount [Integer] How many messages to retrieve. This must be less than or equal to 100, if it is higher # than 100 it will be treated as 100 on Discord's side. # @param before_id [Integer] The ID of the most recent message the retrieval should start at, or nil if it should # start at the current message. # @param after_id [Integer] The ID of the oldest message the retrieval should start at, or nil if it should start # as soon as possible with the specified amount. # @example Count the number of messages in the last 50 messages that contain the letter 'e'. # message_count = channel.history(50).count {|message| message.content.include? "e"} # @return [Array<Message>] the retrieved messages. def history(amount, before_id = nil, after_id = nil) logs = API::Channel.messages(@bot.token, @id, amount, before_id, after_id) JSON.parse(logs).map { |message| Message.new(message, @bot) } end # Retrieves message history, but only message IDs for use with prune # @note For internal use only # @!visibility private def history_ids(amount, before_id = nil, after_id = nil) logs = API::Channel.messages(@bot.token, @id, amount, before_id, after_id) JSON.parse(logs).map { |message| message['id'].to_i } end # Returns a single message from this channel's history by ID. # @param message_id [Integer] The ID of the message to retrieve. # @return [Message] the retrieved message. def load_message(message_id) response = API::Channel.message(@bot.token, @id, message_id) return Message.new(JSON.parse(response), @bot) rescue RestClient::ResourceNotFound return nil end alias_method :message, :load_message # Requests all pinned messages of a channel. # @return [Array<Message>] the received messages. def pins msgs = API::Channel.pinned_messages(@bot.token, @id) JSON.parse(msgs).map { |msg| Message.new(msg, @bot) } end # Delete the last N messages on this channel. # @param amount [Integer] How many messages to delete. Must be a value between 2 and 100 (Discord limitation) # @param strict [true, false] Whether an error should be raised when a message is reached that is too old to be bulk # deleted. If this is false only a warning message will be output to the console. # @raise [ArgumentError] if the amount of messages is not a value between 2 and 100 def prune(amount, strict = false) raise ArgumentError, 'Can only prune between 2 and 100 messages!' unless amount.between?(2, 100) messages = history_ids(amount) bulk_delete(messages, strict) end # Deletes a collection of messages # @param messages [Array<Message, Integer>] the messages (or message IDs) to delete. Total must be an amount between 2 and 100 (Discord limitation) # @param strict [true, false] Whether an error should be raised when a message is reached that is too old to be bulk # deleted. If this is false only a warning message will be output to the console. # @raise [ArgumentError] if the amount of messages is not a value between 2 and 100 def delete_messages(messages, strict = false) raise ArgumentError, 'Can only delete between 2 and 100 messages!' unless messages.count.between?(2, 100) messages.map!(&:resolve_id) bulk_delete(messages, strict) end # Updates the cached permission overwrites # @note For internal use only # @!visibility private def update_overwrites(overwrites) @permission_overwrites = overwrites end # Add an {Await} for a message in this channel. This is identical in functionality to adding a # {Discordrb::Events::MessageEvent} await with the `in` attribute as this channel. # @see Bot#add_await def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { in: @id }.merge(attributes), &block) end # Creates a new invite to this channel. # @param max_age [Integer] How many seconds this invite should last. # @param max_uses [Integer] How many times this invite should be able to be used. # @param temporary [true, false] Whether membership should be temporary (kicked after going offline). # @return [Invite] the created invite. def make_invite(max_age = 0, max_uses = 0, temporary = false) response = API::Channel.create_invite(@bot.token, @id, max_age, max_uses, temporary) Invite.new(JSON.parse(response), @bot) end alias_method :invite, :make_invite # Starts typing, which displays the typing indicator on the client for five seconds. # If you want to keep typing you'll have to resend this every five seconds. (An abstraction # for this will eventually be coming) def start_typing API::Channel.start_typing(@bot.token, @id) end # Creates a Group channel # @param user_ids [Array<Integer>] Array of user IDs to add to the new group channel (Excluding # the recipient of the PM channel). # @return [Channel] the created channel. def create_group(user_ids) raise 'Attempted to create group channel on a non-pm channel!' unless pm? response = API::Channel.create_group(@bot.token, @id, user_ids.shift) channel = Channel.new(JSON.parse(response), @bot) channel.add_group_users(user_ids) end # Adds a user to a Group channel # @param user_ids [Array<#resolve_id>, #resolve_id] User ID or array of user IDs to add to the group channel. # @return [Channel] the group channel. def add_group_users(user_ids) raise 'Attempted to add a user to a non-group channel!' unless group? user_ids = [user_ids] unless user_ids.is_a? Array user_ids.each do |user_id| API::Channel.add_group_user(@bot.token, @id, user_id.resolve_id) end self end alias_method :add_group_user, :add_group_users # Removes a user from a group channel. # @param user_ids [Array<#resolve_id>, #resolve_id] User ID or array of user IDs to remove from the group channel. # @return [Channel] the group channel. def remove_group_users(user_ids) raise 'Attempted to remove a user from a non-group channel!' unless group? user_ids = [user_ids] unless user_ids.is_a? Array user_ids.each do |user_id| API::Channel.remove_group_user(@bot.token, @id, user_id.resolve_id) end self end alias_method :remove_group_user, :remove_group_users # Leaves the group def leave_group raise 'Attempted to leave a non-group channel!' unless group? API::Channel.leave_group(@bot.token, @id) end alias_method :leave, :leave_group # The inspect method is overwritten to give more useful output def inspect "<Channel name=#{@name} id=#{@id} topic=\"#{@topic}\" type=#{@type} position=#{@position} server=#{@server}>" end # Adds a recipient to a group channel. # @param recipient [Recipient] the recipient to add to the group # @raise [ArgumentError] if tried to add a non-recipient # @note For internal use only # @!visibility private def add_recipient(recipient) raise 'Tried to add recipient to a non-group channel' unless group? raise ArgumentError, 'Tried to add a non-recipient to a group' unless recipient.is_a?(Recipient) @recipients << recipient end # Removes a recipient from a group channel. # @param recipient [Recipient] the recipient to remove from the group # @raise [ArgumentError] if tried to remove a non-recipient # @note For internal use only # @!visibility private def remove_recipient(recipient) raise 'Tried to remove recipient from a non-group channel' unless group? raise ArgumentError, 'Tried to remove a non-recipient from a group' unless recipient.is_a?(Recipient) @recipients.delete(recipient) end private # For bulk_delete checking TWO_WEEKS = 86_400 * 14 # Deletes a list of messages on this channel using bulk delete def bulk_delete(ids, strict = false) min_snowflake = IDObject.synthesise(Time.now - TWO_WEEKS) ids.reject! do |e| next unless e < min_snowflake message = "Attempted to bulk_delete message #{e} which is too old (min = #{min_snowflake})" raise ArgumentError, message if strict Discordrb::LOGGER.warn(message) false end API::Channel.bulk_delete_messages(@bot.token, @id, ids) end def update_channel_data API::Channel.update(@bot.token, @id, @name, @topic, @position, @bitrate, @user_limit) end end # An Embed object that is contained in a message # A freshly generated embed object will not appear in a message object # unless grabbed from its ID in a channel. class Embed # @return [Message] the message this embed object is contained in. attr_reader :message # @return [String] the URL this embed object is based on. attr_reader :url # @return [String, nil] the title of the embed object. `nil` if there is not a title attr_reader :title # @return [String, nil] the description of the embed object. `nil` if there is not a description attr_reader :description # @return [Symbol] the type of the embed object. Possible types are: # # * `:link` # * `:video` # * `:image` attr_reader :type # @return [EmbedProvider, nil] the provider of the embed object. `nil` is there is not a provider attr_reader :provider # @return [EmbedThumbnail, nil] the thumbnail of the embed object. `nil` is there is not a thumbnail attr_reader :thumbnail # @return [EmbedAuthor, nil] the author of the embed object. `nil` is there is not an author attr_reader :author # @!visibility private def initialize(data, message) @message = message @url = data['url'] @title = data['title'] @type = data['type'].to_sym @description = data['description'] @provider = data['provider'].nil? ? nil : EmbedProvider.new(data['provider'], self) @thumbnail = data['thumbnail'].nil? ? nil : EmbedThumbnail.new(data['thumbnail'], self) @author = data['author'].nil? ? nil : EmbedAuthor.new(data['author'], self) end end # An Embed thumbnail for the embed object class EmbedThumbnail # @return [Embed] the embed object this is based on. attr_reader :embed # @return [String] the CDN URL this thumbnail can be downloaded at. attr_reader :url # @return [String] the thumbnail's proxy URL - I'm not sure what exactly this does, but I think it has something to # do with CDNs attr_reader :proxy_url # @return [Integer] the width of this thumbnail file, in pixels. attr_reader :width # @return [Integer] the height of this thumbnail file, in pixels. attr_reader :height # @!visibility private def initialize(data, embed) @embed = embed @url = data['url'] @proxy_url = data['proxy_url'] @width = data['width'] @height = data['height'] end end # An Embed provider for the embed object class EmbedProvider # @return [Embed] the embed object this is based on. attr_reader :embed # @return [String] the provider's name. attr_reader :name # @return [String, nil] the URL of the provider. `nil` is there is no URL attr_reader :url # @!visibility private def initialize(data, embed) @embed = embed @name = data['name'] @url = data['url'] end end # An Embed author for the embed object class EmbedAuthor # @return [Embed] the embed object this is based on. attr_reader :embed # @return [String] the author's name. attr_reader :name # @return [String, nil] the URL of the author's website. `nil` is there is no URL attr_reader :url # @!visibility private def initialize(data, embed) @embed = embed @name = data['name'] @url = data['url'] end end # An attachment to a message class Attachment include IDObject # @return [Message] the message this attachment belongs to. attr_reader :message # @return [String] the CDN URL this attachment can be downloaded at. attr_reader :url # @return [String] the attachment's proxy URL - I'm not sure what exactly this does, but I think it has something to # do with CDNs attr_reader :proxy_url # @return [String] the attachment's filename. attr_reader :filename # @return [Integer] the attachment's file size in bytes. attr_reader :size # @return [Integer, nil] the width of an image file, in pixels, or nil if the file is not an image. attr_reader :width # @return [Integer, nil] the height of an image file, in pixels, or nil if the file is not an image. attr_reader :height # @!visibility private def initialize(data, message, bot) @bot = bot @message = message @url = data['url'] @proxy_url = data['proxy_url'] @filename = data['filename'] @size = data['size'] @width = data['width'] @height = data['height'] end # @return [true, false] whether this file is an image file. def image? !(@width.nil? || @height.nil?) end end # A message on Discord that was sent to a text channel class Message include IDObject # @return [String] the content of this message. attr_reader :content alias_method :text, :content alias_method :to_s, :content # @return [Member, User] the user that sent this message. (Will be a {Member} most of the time, it should only be a # {User} for old messages when the author has left the server since then) attr_reader :author alias_method :user, :author alias_method :writer, :author # @return [Channel] the channel in which this message was sent. attr_reader :channel # @return [Time] the timestamp at which this message was sent. attr_reader :timestamp # @return [Time] the timestamp at which this message was edited. `nil` if the message was never edited. attr_reader :edited_timestamp alias_method :edit_timestamp, :edited_timestamp # @return [Array<User>] the users that were mentioned in this message. attr_reader :mentions # @return [Array<Role>] the roles that were mentioned in this message. attr_reader :role_mentions # @return [Array<Attachment>] the files attached to this message. attr_reader :attachments # @return [Array<Embed>] the embed objects contained in this message. attr_reader :embeds # @return [Hash<String, Reaction>] the reaction objects attached to this message keyed by the name of the reaction attr_reader :reactions # @return [true, false] whether the message used Text-To-Speech (TTS) or not. attr_reader :tts alias_method :tts?, :tts # @return [String] used for validating a message was sent attr_reader :nonce # @return [true, false] whether the message was edited or not. attr_reader :edited alias_method :edited?, :edited # @return [true, false] whether the message mentioned everyone or not. attr_reader :mention_everyone alias_method :mention_everyone?, :mention_everyone alias_method :mentions_everyone?, :mention_everyone # @return [true, false] whether the message is pinned or not. attr_reader :pinned alias_method :pinned?, :pinned # @return [Integer, nil] the webhook ID that sent this message, or nil if it wasn't sent through a webhook. attr_reader :webhook_id # The discriminator that webhook user accounts have. ZERO_DISCRIM = '0000'.freeze # @!visibility private def initialize(data, bot) @bot = bot @content = data['content'] @channel = bot.channel(data['channel_id'].to_i) @pinned = data['pinned'] @tts = data['tts'] @nonce = data['nonce'] @mention_everyone = data['mention_everyone'] @author = if data['author'] if data['author']['discriminator'] == ZERO_DISCRIM # This is a webhook user! It would be pointless to try to resolve a member here, so we just create # a User and return that instead. Discordrb::LOGGER.debug("Webhook user: #{data['author']['id']}") User.new(data['author'], @bot) elsif @channel.private? # Turn the message user into a recipient - we can't use the channel recipient # directly because the bot may also send messages to the channel Recipient.new(bot.user(data['author']['id'].to_i), @channel, bot) else member = @channel.server.member(data['author']['id'].to_i) unless member Discordrb::LOGGER.debug("Member with ID #{data['author']['id']} not cached (possibly left the server).") member = @bot.user(data['author']['id'].to_i) end member end end @webhook_id = data['webhook_id'].to_i if data['webhook_id'] @timestamp = Time.parse(data['timestamp']) if data['timestamp'] @edited_timestamp = data['edited_timestamp'].nil? ? nil : Time.parse(data['edited_timestamp']) @edited = !@edited_timestamp.nil? @id = data['id'].to_i @emoji = [] @reactions = {} if data['reactions'] data['reactions'].each do |element| @reactions[element['emoji']['name']] = Reaction.new(element) end end @mentions = [] if data['mentions'] data['mentions'].each do |element| @mentions << bot.ensure_user(element) end end @role_mentions = [] # Role mentions can only happen on public servers so make sure we only parse them there if @channel.text? if data['mention_roles'] data['mention_roles'].each do |element| @role_mentions << @channel.server.role(element.to_i) end end end @attachments = [] @attachments = data['attachments'].map { |e| Attachment.new(e, self, @bot) } if data['attachments'] @embeds = [] @embeds = data['embeds'].map { |e| Embed.new(e, self) } if data['embeds'] end # Replies to this message with the specified content. # @see Channel#send_message def reply(content) @channel.send_message(content) end # Edits this message to have the specified content instead. # You can only edit your own messages. # @param new_content [String] the new content the message should have. # @param new_embed [Hash, Discordrb::Webhooks::Embed, nil] The new embed the message should have. If nil the message will be changed to have no embed. # @return [Message] the resulting message. def edit(new_content, new_embed = nil) response = API::Channel.edit_message(@bot.token, @channel.id, @id, new_content, [], new_embed ? new_embed.to_hash : nil) Message.new(JSON.parse(response), @bot) end # Deletes this message. def delete API::Channel.delete_message(@bot.token, @channel.id, @id) nil end # Pins this message def pin API::Channel.pin_message(@bot.token, @channel.id, @id) @pinned = true nil end # Unpins this message def unpin API::Channel.unpin_message(@bot.token, @channel.id, @id) @pinned = false nil end # Add an {Await} for a message with the same user and channel. # @see Bot#add_await def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { from: @author.id, in: @channel.id }.merge(attributes), &block) end # @return [true, false] whether this message was sent by the current {Bot}. def from_bot? @author && @author.current_bot? end # @return [true, false] whether this message has been sent over a webhook. def webhook? !@webhook_id.nil? end # @!visibility private # @return [Array<String>] the emoji mentions found in the message def scan_for_emoji emoji = @content.split emoji = emoji.grep(/<:(?<name>\w+):(?<id>\d+)>?/) emoji end # @return [Array<Emoji>] the emotes that were used/mentioned in this message (Only returns Emoji the bot has access to, else nil). def emoji return if @content.nil? emoji = scan_for_emoji emoji.each do |element| @emoji << @bot.parse_mention(element) end @emoji end # Check if any emoji got used in this message # @return [true, false] whether or not any emoji got used def emoji? emoji = scan_for_emoji return true unless emoji.empty? end # Check if any reactions got used in this message # @return [true, false] whether or not this message has reactions def reactions? @reactions.any? end # Returns the reactions made by the current bot or user # @return [Array<Reaction>] the reactions def my_reactions @reactions.select(&:me) end # Reacts to a message # @param [String, #to_reaction] the unicode emoji, Emoji, or GlobalEmoji def create_reaction(reaction) reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction) API::Channel.create_reaction(@bot.token, @channel.id, @id, reaction) nil end alias_method :react, :create_reaction # Returns the list of users who reacted with a certain reaction # @param [String, #to_reaction] the unicode emoji, Emoji, or GlobalEmoji # @return [Array<User>] the users who used this reaction def reacted_with(reaction) reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction) response = JSON.parse(API::Channel.get_reactions(@bot.token, @channel.id, @id, reaction)) response.map { |d| User.new(d, @bot) } end # Deletes a reaction made by a user on this message # @param [User, #resolve_id] the user who used this reaction # @param [String, #to_reaction] the reaction to remove def delete_reaction(user, reaction) reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction) API::Channel.delete_user_reaction(@bot.token, @channel.id, @id, reaction, user.resolve_id) end # Delete's this clients reaction on this message # @param [String, #to_reaction] the reaction to remove def delete_own_reaction(reaction) reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction) API::Channel.delete_own_reaction(@bot.token, @channel.id, @id, reaction) end # Removes all reactions from this message def delete_all_reactions API::Channel.delete_all_reactions(@bot.token, @channel.id, @id) end # The inspect method is overwritten to give more useful output def inspect "<Message content=\"#{@content}\" id=#{@id} timestamp=#{@timestamp} author=#{@author} channel=#{@channel}>" end end # A reaction to a message class Reaction # @return [Integer] the amount of users who have reacted with this reaction attr_reader :count # @return [true, false] whether the current bot or user used this reaction attr_reader :me alias_method :me?, :me # @return [Integer] the ID of the emoji, if it was custom attr_reader :id # @return [String] the name or unicode representation of the emoji attr_reader :name def initialize(data) @count = data['count'] @me = data['me'] @id = data['emoji']['id'].nil? ? nil : data['emoji']['id'].to_i @name = data['emoji']['name'] end end # Server emoji class Emoji include IDObject # @return [String] the emoji name attr_reader :name # @return [Server] the server of this emoji attr_reader :server # @return [Array<Role>] roles this emoji is active for attr_reader :roles def initialize(data, bot, server) @bot = bot @roles = nil @name = data['name'] @server = server @id = data['id'].nil? ? nil : data['id'].to_i process_roles(data['roles']) if server end # @return [String] the layout to mention it (or have it used) in a message def mention "<:#{@name}:#{@id}>" end alias_method :use, :mention alias_method :to_s, :mention # @return [String] the layout to use this emoji in a reaction def to_reaction "#{@name}:#{@id}" end # @return [String] the icon URL of the emoji def icon_url API.emoji_icon_url(@id) end # The inspect method is overwritten to give more useful output def inspect "<Emoji name=#{@name} id=#{@id}>" end # @!visibility private def process_roles(roles) @roles = [] return unless roles roles.each do |role_id| role = server.role(role_id) @roles << role end end end # Emoji that is not tailored to a server class GlobalEmoji include IDObject # @return [String] the emoji name attr_reader :name # @return [Hash<Integer => Array<Role>>] roles this emoji is active for in every server attr_reader :role_associations def initialize(data, bot) @bot = bot @roles = nil @name = data.name @id = data.id @role_associations = Hash.new([]) @role_associations[data.server.id] = data.roles end # @return [String] the layout to mention it (or have it used) in a message def mention "<:#{@name}:#{@id}>" end alias_method :use, :mention alias_method :to_s, :mention # @return [String] the layout to use this emoji in a reaction def to_reaction "#{@name}:#{@id}" end # @return [String] the icon URL of the emoji def icon_url API.emoji_icon_url(@id) end # The inspect method is overwritten to give more useful output def inspect "<GlobalEmoji name=#{@name} id=#{@id}>" end # @!visibility private def process_roles(roles) new_roles = [] return unless roles roles.each do role = server.role(role_id) new_roles << role end new_roles end end # Basic attributes a server should have module ServerAttributes # @return [String] this server's name. attr_reader :name # @return [String] the hexadecimal ID used to identify this server's icon. attr_reader :icon_id # Utility function to get the URL for the icon image # @return [String] the URL to the icon image def icon_url return nil unless @icon_id API.icon_url(@id, @icon_id) end end # Integration Account class IntegrationAccount # @return [String] this account's name. attr_reader :name # @return [Integer] this account's ID. attr_reader :id def initialize(data) @name = data['name'] @id = data['id'].to_i end end # Server integration class Integration include IDObject # @return [String] the integration name attr_reader :name # @return [Server] the server the integration is linked to attr_reader :server # @return [User] the user the integration is linked to attr_reader :user # @return [Role, nil] the role that this integration uses for "subscribers" attr_reader :role # @return [true, false] whether emoticons are enabled attr_reader :emoticon alias_method :emoticon?, :emoticon # @return [String] the integration type (Youtube, Twitch, etc.) attr_reader :type # @return [true, false] whether the integration is enabled attr_reader :enabled # @return [true, false] whether the integration is syncing attr_reader :syncing # @return [IntegrationAccount] the integration account information attr_reader :account # @return [Time] the time the integration was synced at attr_reader :synced_at # @return [Symbol] the behaviour of expiring subscribers (:remove = Remove User from role; :kick = Kick User from server) attr_reader :expire_behaviour alias_method :expire_behavior, :expire_behaviour # @return [Integer] the grace period before subscribers expire (in days) attr_reader :expire_grace_period def initialize(data, bot, server) @bot = bot @name = data['name'] @server = server @id = data['id'].to_i @enabled = data['enabled'] @syncing = data['syncing'] @type = data['type'] @account = IntegrationAccount.new(data['account']) @synced_at = Time.parse(data['synced_at']) @expire_behaviour = [:remove, :kick][data['expire_behavior']] @expire_grace_period = data['expire_grace_period'] @user = @bot.ensure_user(data['user']) @role = server.role(data['role_id']) || nil @emoticon = data['enable_emoticons'] end # The inspect method is overwritten to give more useful output def inspect "<Integration name=#{@name} id=#{@id} type=#{@type} enabled=#{@enabled}>" end end # A server on Discord class Server include IDObject include ServerAttributes # @return [String] the region the server is on (e. g. `amsterdam`). attr_reader :region # @return [Member] The server owner. attr_reader :owner # @return [Array<Channel>] an array of all the channels (text and voice) on this server. attr_reader :channels # @return [Array<Role>] an array of all the roles created on this server. attr_reader :roles # @return [Hash<Integer, Emoji>] a hash of all the emoji available on this server. attr_reader :emoji alias_method :emojis, :emoji # @return [true, false] whether or not this server is large (members > 100). If it is, # it means the members list may be inaccurate for a couple seconds after starting up the bot. attr_reader :large alias_method :large?, :large # @return [Array<Symbol>] the features of the server (eg. "INVITE_SPLASH") attr_reader :features # @return [Integer] the absolute number of members on this server, offline or not. attr_reader :member_count # @return [Symbol] the verification level of the server (:none = none, :low = 'Must have a verified email on their Discord account', :medium = 'Has to be registered with Discord for at least 5 minutes', :high = 'Has to be a member of this server for at least 10 minutes'). attr_reader :verification_level # @return [Integer] the amount of time after which a voice user gets moved into the AFK channel, in seconds. attr_reader :afk_timeout # @return [Channel, nil] the AFK voice channel of this server, or nil if none is set attr_reader :afk_channel # @return [Hash<Integer => VoiceState>] the hash (user ID => voice state) of voice states of members on this server attr_reader :voice_states # @!visibility private def initialize(data, bot, exists = true) @bot = bot @owner_id = data['owner_id'].to_i @id = data['id'].to_i update_data(data) @large = data['large'] @member_count = data['member_count'] @verification_level = [:none, :low, :medium, :high][data['verification_level']] @splash_id = nil @embed = nil @features = data['features'].map { |element| element.downcase.to_sym } @members = {} @voice_states = {} @emoji = {} process_roles(data['roles']) process_emoji(data['emojis']) process_members(data['members']) process_presences(data['presences']) process_channels(data['channels']) process_voice_states(data['voice_states']) # Whether this server's members have been chunked (resolved using op 8 and GUILD_MEMBERS_CHUNK) yet @chunked = false @processed_chunk_members = 0 # Only get the owner of the server actually exists (i. e. not for ServerDeleteEvent) @owner = member(@owner_id) if exists end # @return [Channel] The default channel on this server (usually called #general) def default_channel @bot.channel(@id) end alias_method :general_channel, :default_channel # Gets a role on this server based on its ID. # @param id [Integer, String, #resolve_id] The role ID to look for. def role(id) id = id.resolve_id @roles.find { |e| e.id == id } end # Gets a member on this server based on user ID # @param id [Integer] The user ID to look for # @param request [true, false] Whether the member should be requested from Discord if it's not cached def member(id, request = true) id = id.resolve_id return @members[id] if member_cached?(id) return nil unless request member = @bot.member(self, id) @members[id] = member rescue nil end # @return [Array<Member>] an array of all the members on this server. def members return @members.values if @chunked @bot.debug("Members for server #{@id} not chunked yet - initiating") @bot.request_chunks(@id) sleep 0.05 until @chunked @members.values end alias_method :users, :members # @return [Array<Integration>] an array of all the integrations connected to this server. def integrations integration = JSON.parse(API::Server.integrations(@bot.token, @id)) integration.map { |element| Integration.new(element, @bot, self) } end # Cache @embed # @note For internal use only # @!visibility private def cache_embed @embed ||= JSON.parse(API::Server.resolve(@bot.token, @id))['embed_enabled'] end # @return [true, false] whether or not the server has widget enabled def embed? cache_embed if @embed.nil? @embed end # @param include_idle [true, false] Whether to count idle members as online. # @param include_bots [true, false] Whether to include bot accounts in the count. # @return [Array<Member>] an array of online members on this server. def online_members(include_idle: false, include_bots: true) @members.values.select do |e| ((include_idle ? e.idle? : false) || e.online?) && (include_bots ? true : !e.bot_account?) end end alias_method :online_users, :online_members # @return [Array<Channel>] an array of text channels on this server def text_channels @channels.select(&:text?) end # @return [Array<Channel>] an array of voice channels on this server def voice_channels @channels.select(&:voice?) end # @return [String, nil] the widget URL to the server that displays the amount of online members in a # stylish way. `nil` if the widget is not enabled. def widget_url cache_embed if @embed.nil? return nil unless @embed API.widget_url(@id) end # @param style [Symbol] The style the picture should have. Possible styles are: # * `:banner1` creates a rectangular image with the server name, member count and icon, a "Powered by Discord" message on the bottom and an arrow on the right. # * `:banner2` creates a less tall rectangular image that has the same information as `banner1`, but the Discord logo on the right - together with the arrow and separated by a diagonal separator. # * `:banner3` creates an image similar in size to `banner1`, but it has the arrow in the bottom part, next to the Discord logo and with a "Chat now" text. # * `:banner4` creates a tall, almost square, image that prominently features the Discord logo at the top and has a "Join my server" in a pill-style button on the bottom. The information about the server is in the same format as the other three `banner` styles. # * `:shield` creates a very small, long rectangle, of the style you'd find at the top of GitHub `README.md` files. It features a small version of the Discord logo at the left and the member count at the right. # @return [String, nil] the widget banner URL to the server that displays the amount of online members, # server icon and server name in a stylish way. `nil` if the widget is not enabled. def widget_banner_url(style) return nil unless @embed cache_embed if @embed.nil? API.widget_url(@id, style) end # @return [String] the hexadecimal ID used to identify this server's splash image for their VIP invite page. def splash_id @splash_id ||= JSON.parse(API::Server.resolve(@bot.token, @id))['splash'] end # @return [String, nil] the splash image URL for the server's VIP invite page. # `nil` if there is no splash image. def splash_url splash_id if @splash_id.nil? return nil unless @splash_id API.splash_url(@id, @splash_id) end # Adds a role to the role cache # @note For internal use only # @!visibility private def add_role(role) @roles << role end # Removes a role from the role cache # @note For internal use only # @!visibility private def delete_role(role_id) @roles.reject! { |r| r.id == role_id } @members.each do |_, member| new_roles = member.roles.reject { |r| r.id == role_id } member.update_roles(new_roles) end @channels.each do |channel| overwrites = channel.permission_overwrites.reject { |id, _| id == role_id } channel.update_overwrites(overwrites) end end # Adds a member to the member cache. # @note For internal use only # @!visibility private def add_member(member) @members[member.id] = member @member_count += 1 end # Removes a member from the member cache. # @note For internal use only # @!visibility private def delete_member(user_id) @members.delete(user_id) @member_count -= 1 end # Checks whether a member is cached # @note For internal use only # @!visibility private def member_cached?(user_id) @members.include?(user_id) end # Adds a member to the cache # @note For internal use only # @!visibility private def cache_member(member) @members[member.id] = member end # Updates a member's voice state # @note For internal use only # @!visibility private def update_voice_state(data) user_id = data['user_id'].to_i if data['channel_id'] unless @voice_states[user_id] # Create a new voice state for the user @voice_states[user_id] = VoiceState.new(user_id) end # Update the existing voice state (or the one we just created) channel = @channels_by_id[data['channel_id'].to_i] @voice_states[user_id].update( channel, data['mute'], data['deaf'], data['self_mute'], data['self_deaf'] ) else # The user is not in a voice channel anymore, so delete its voice state @voice_states.delete(user_id) end end # Creates a channel on this server with the given name. # @param name [String] Name of the channel to create # @param type [Integer] Type of channel to create (0: text, 2: voice) # @return [Channel] the created channel. # @raise [ArgumentError] if type is not 0 or 2 def create_channel(name, type = 0) raise ArgumentError, 'Channel type must be either 0 (text) or 2 (voice)!' unless [0, 2].include?(type) response = API::Server.create_channel(@bot.token, @id, name, type) Channel.new(JSON.parse(response), @bot) end # Creates a role on this server which can then be modified. It will be initialized (on Discord's side) # with the regular role defaults the client uses, i. e. name is "new role", permissions are the default, # colour is the default etc. # @return [Role] the created role. def create_role response = API::Server.create_role(@bot.token, @id) role = Role.new(JSON.parse(response), @bot, self) @roles << role role end # @return [Array<User>] a list of banned users on this server. def bans users = JSON.parse(API::Server.bans(@bot.token, @id)) users.map { |e| User.new(e['user'], @bot) } end # Bans a user from this server. # @param user [User, #resolve_id] The user to ban. # @param message_days [Integer] How many days worth of messages sent by the user should be deleted. def ban(user, message_days = 0) API::Server.ban_user(@bot.token, @id, user.resolve_id, message_days) end # Unbans a previously banned user from this server. # @param user [User, #resolve_id] The user to unban. def unban(user) API::Server.unban_user(@bot.token, @id, user.resolve_id) end # Kicks a user from this server. # @param user [User, #resolve_id] The user to kick. def kick(user) API::Server.remove_member(@bot.token, @id, user.resolve_id) end # Forcibly moves a user into a different voice channel. Only works if the bot has the permission needed. # @param user [User] The user to move. # @param channel [Channel] The voice channel to move into. def move(user, channel) API::Server.update_member(@bot.token, @id, user.id, channel_id: channel.id) end # Deletes this server. Be aware that this is permanent and impossible to undo, so be careful! def delete API::Server.delete(@bot.token, @id) end # Leave the server def leave API::User.leave_server(@bot.token, @id) end # Transfers server ownership to another user. # @param user [User] The user who should become the new owner. def owner=(user) API::Server.transfer_ownership(@bot.token, @id, user.id) end # Sets the server's name. # @param name [String] The new server name. def name=(name) update_server_data(name: name) end # Moves the server to another region. This will cause a voice interruption of at most a second. # @param region [String] The new region the server should be in. def region=(region) update_server_data(region: region.to_s) end # Sets the server's icon. # @param icon [String, #read] The new icon, in base64-encoded JPG format. def icon=(icon) if icon.respond_to? :read icon_string = 'data:image/jpg;base64,' icon_string += Base64.strict_encode64(icon.read) update_server_data(icon: icon_string) else update_server_data(icon: icon) end end # Sets the server's AFK channel. # @param afk_channel [Channel, nil] The new AFK channel, or `nil` if there should be none set. def afk_channel=(afk_channel) update_server_data(afk_channel_id: afk_channel.resolve_id) end # Sets the amount of time after which a user gets moved into the AFK channel. # @param afk_timeout [Integer] The AFK timeout, in seconds. def afk_timeout=(afk_timeout) update_server_data(afk_timeout: afk_timeout) end # @return [true, false] whether this server has any emoji or not. def any_emoji? @emoji.any? end alias_method :has_emoji?, :any_emoji? alias_method :emoji?, :any_emoji? # Processes a GUILD_MEMBERS_CHUNK packet, specifically the members field # @note For internal use only # @!visibility private def process_chunk(members) process_members(members) @processed_chunk_members += members.length LOGGER.debug("Processed one chunk on server #{@id} - length #{members.length}") # Don't bother with the rest of the method if it's not truly the last packet return unless @processed_chunk_members == @member_count LOGGER.debug("Finished chunking server #{@id}") # Reset everything to normal @chunked = true @processed_chunk_members = 0 end # Updates the cached data with new data # @note For internal use only # @!visibility private def update_data(new_data) @name = new_data[:name] || new_data['name'] || @name @region = new_data[:region] || new_data['region'] || @region @icon_id = new_data[:icon] || new_data['icon'] || @icon_id @afk_timeout = new_data[:afk_timeout] || new_data['afk_timeout'].to_i || @afk_timeout @afk_channel_id = new_data[:afk_channel_id] || new_data['afk_channel_id'].to_i || @afk_channel.id begin @afk_channel = @bot.channel(@afk_channel_id, self) if @afk_channel_id.nonzero? && (!@afk_channel || @afk_channel_id != @afk_channel.id) rescue Discordrb::Errors::NoPermission LOGGER.debug("AFK channel #{@afk_channel_id} on server #{@id} is unreachable, setting to nil even though one exists") @afk_channel = nil end end # Adds a channel to this server's cache # @note For internal use only # @!visibility private def add_channel(channel) @channels << channel @channels_by_id[channel.id] = channel end # Deletes a channel from this server's cache # @note For internal use only # @!visibility private def delete_channel(id) @channels.reject! { |e| e.id == id } @channels_by_id.delete(id) end # Updates the cached emoji data with new data # @note For internal use only # @!visibility private def update_emoji_data(new_data) @emoji = {} process_emoji(new_data['emojis']) end # The inspect method is overwritten to give more useful output def inspect "<Server name=#{@name} id=#{@id} large=#{@large} region=#{@region} owner=#{@owner} afk_channel_id=#{@afk_channel_id} afk_timeout=#{@afk_timeout}>" end private def update_server_data(new_data) API::Server.update(@bot.token, @id, new_data[:name] || @name, new_data[:region] || @region, new_data[:icon_id] || @icon_id, new_data[:afk_channel_id] || @afk_channel_id, new_data[:afk_timeout] || @afk_timeout) update_data(new_data) end def process_roles(roles) # Create roles @roles = [] @roles_by_id = {} return unless roles roles.each do |element| role = Role.new(element, @bot, self) @roles << role @roles_by_id[role.id] = role end end def process_emoji(emoji) return if emoji.empty? emoji.each do |element| new_emoji = Emoji.new(element, @bot, self) @emoji[new_emoji.id] = new_emoji end end def process_members(members) return unless members members.each do |element| member = Member.new(element, self, @bot) @members[member.id] = member end end def process_presences(presences) # Update user statuses with presence info return unless presences presences.each do |element| next unless element['user'] user_id = element['user']['id'].to_i user = @members[user_id] if user user.update_presence(element) else LOGGER.warn "Rogue presence update! #{element['user']['id']} on #{@id}" end end end def process_channels(channels) @channels = [] @channels_by_id = {} return unless channels channels.each do |element| channel = @bot.ensure_channel(element, self) @channels << channel @channels_by_id[channel.id] = channel end end def process_voice_states(voice_states) return unless voice_states voice_states.each do |element| update_voice_state(element) end end end # A colour (red, green and blue values). Used for role colours. If you prefer the American spelling, the alias # {ColorRGB} is also available. class ColourRGB # @return [Integer] the red part of this colour (0-255). attr_reader :red # @return [Integer] the green part of this colour (0-255). attr_reader :green # @return [Integer] the blue part of this colour (0-255). attr_reader :blue # @return [Integer] the colour's RGB values combined into one integer. attr_reader :combined # Make a new colour from the combined value. # @param combined [Integer] The colour's RGB values combined into one integer def initialize(combined) @combined = combined @red = (combined >> 16) & 0xFF @green = (combined >> 8) & 0xFF @blue = combined & 0xFF end end # Alias for the class {ColourRGB} ColorRGB = ColourRGB end support around_id in Channel#history # frozen_string_literal: true # These classes hold relevant Discord data, such as messages or channels. require 'ostruct' require 'discordrb/permissions' require 'discordrb/errors' require 'discordrb/api' require 'discordrb/api/channel' require 'discordrb/api/server' require 'discordrb/api/invite' require 'discordrb/api/user' require 'discordrb/webhooks/embeds' require 'time' require 'base64' # Discordrb module module Discordrb # The unix timestamp Discord IDs are based on DISCORD_EPOCH = 1_420_070_400_000 # Compares two objects based on IDs - either the objects' IDs are equal, or one object is equal to the other's ID. def self.id_compare(one_id, other) other.respond_to?(:resolve_id) ? (one_id.resolve_id == other.resolve_id) : (one_id == other) end # The maximum length a Discord message can have CHARACTER_LIMIT = 2000 # Splits a message into chunks of 2000 characters. Attempts to split by lines if possible. # @param msg [String] The message to split. # @return [Array<String>] the message split into chunks def self.split_message(msg) # If the messages is empty, return an empty array return [] if msg.empty? # Split the message into lines lines = msg.lines # Turn the message into a "triangle" of consecutively longer slices, for example the array [1,2,3,4] would become # [ # [1], # [1, 2], # [1, 2, 3], # [1, 2, 3, 4] # ] tri = [*0..(lines.length - 1)].map { |i| lines.combination(i + 1).first } # Join the individual elements together to get an array of strings with consecutively more lines joined = tri.map(&:join) # Find the largest element that is still below the character limit, or if none such element exists return the first ideal = joined.max_by { |e| e.length > CHARACTER_LIMIT ? -1 : e.length } # If it's still larger than the character limit (none was smaller than it) split it into slices with the length # being the character limit, otherwise just return an array with one element ideal_ary = ideal.length > CHARACTER_LIMIT ? ideal.chars.each_slice(CHARACTER_LIMIT).map(&:join) : [ideal] # Slice off the ideal part and strip newlines rest = msg[ideal.length..-1].strip # If none remains, return an empty array -> we're done return [] unless rest # Otherwise, call the method recursively to split the rest of the string and add it onto the ideal array ideal_ary + split_message(rest) end # Mixin for objects that have IDs module IDObject # @return [Integer] the ID which uniquely identifies this object across Discord. attr_reader :id alias_method :resolve_id, :id # ID based comparison def ==(other) Discordrb.id_compare(@id, other) end # Estimates the time this object was generated on based on the beginning of the ID. This is fairly accurate but # shouldn't be relied on as Discord might change its algorithm at any time # @return [Time] when this object was created at def creation_time # Milliseconds ms = (@id >> 22) + DISCORD_EPOCH Time.at(ms / 1000.0) end # Creates an artificial snowflake at the given point in time. Useful for comparing against. # @param time [Time] The time the snowflake should represent. # @return [Integer] a snowflake with the timestamp data as the given time def self.synthesise(time) ms = (time.to_f * 1000).to_i (ms - DISCORD_EPOCH) << 22 end class << self alias_method :synthesize, :synthesise end end # Mixin for the attributes users should have module UserAttributes # @return [String] this user's username attr_reader :username alias_method :name, :username # @return [String] this user's discriminator which is used internally to identify users with identical usernames. attr_reader :discriminator alias_method :discrim, :discriminator alias_method :tag, :discriminator alias_method :discord_tag, :discriminator # @return [true, false] whether this user is a Discord bot account attr_reader :bot_account alias_method :bot_account?, :bot_account # @return [String] the ID of this user's current avatar, can be used to generate an avatar URL. # @see #avatar_url attr_accessor :avatar_id # Utility function to mention users in messages # @return [String] the mention code in the form of <@id> def mention "<@#{@id}>" end # Utility function to get Discord's distinct representation of a user, i. e. username + discriminator # @return [String] distinct representation of user def distinct "#{@username}##{@discriminator}" end # Utility function to get a user's avatar URL. # @return [String] the URL to the avatar image. def avatar_url API::User.avatar_url(@id, @avatar_id) end end # User on Discord, including internal data like discriminators class User include IDObject include UserAttributes # @return [Symbol] the current online status of the user (`:online`, `:offline` or `:idle`) attr_reader :status # @return [String, nil] the game the user is currently playing, or `nil` if none is being played. attr_reader :game # @return [String, nil] the URL to the stream, if the user is currently streaming something. attr_reader :stream_url # @return [String, Integer, nil] the type of the stream. Can technically be set to anything, most of the time it # will be 0 for no stream or 1 for Twitch streams. attr_reader :stream_type def initialize(data, bot) @bot = bot @username = data['username'] @id = data['id'].to_i @discriminator = data['discriminator'] @avatar_id = data['avatar'] @roles = {} @bot_account = false @bot_account = true if data['bot'] @status = :offline end # Get a user's PM channel or send them a PM # @overload pm # Creates a private message channel for this user or returns an existing one if it already exists # @return [Channel] the PM channel to this user. # @overload pm(content) # Sends a private to this user. # @param content [String] The content to send. # @return [Message] the message sent to this user. def pm(content = nil) if content # Recursively call pm to get the channel, then send a message to it channel = pm channel.send_message(content) else # If no message was specified, return the PM channel @bot.pm_channel(@id) end end alias_method :dm, :pm # Send the user a file. # @param file [File] The file to send to the user # @param caption [String] The caption of the file being sent # @return [Message] the message sent to this user. def send_file(file, caption = nil) pm.send_file(file, caption: caption) end # Set the user's name # @note for internal use only # @!visibility private def update_username(username) @username = username end # Set the user's presence data # @note for internal use only # @!visibility private def update_presence(data) @status = data['status'].to_sym if data['game'] game = data['game'] @game = game['name'] @stream_url = game['url'] @stream_type = game['type'] else @game = @stream_url = @stream_type = nil end end # Add an await for a message from this user. Specifically, this adds a global await for a MessageEvent with this # user's ID as a :from attribute. # @see Bot#add_await def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { from: @id }.merge(attributes), &block) end # Gets the member this user is on a server # @param server [Server] The server to get the member for # @return [Member] this user as a member on a particular server def on(server) id = server.resolve_id @bot.server(id).member(@id) end # Is the user the bot? # @return [true, false] whether this user is the bot def current_bot? @bot.profile.id == @id end # @return [true, false] whether this user is a fake user for a webhook message def webhook? @discriminator == Message::ZERO_DISCRIM end [:offline, :idle, :online].each do |e| define_method(e.to_s + '?') do @status.to_sym == e end end # The inspect method is overwritten to give more useful output def inspect "<User username=#{@username} id=#{@id} discriminator=#{@discriminator}>" end end # OAuth Application information class Application include IDObject # @return [String] the application name attr_reader :name # @return [String] the application description attr_reader :description # @return [Array<String>] the applications origins permitted to use RPC attr_reader :rpc_origins # @return [Integer] attr_reader :flags # Gets the user object of the owner. May be limited to username, discriminator, # ID and avatar if the bot cannot reach the owner. # @return [User] the user object of the owner attr_reader :owner def initialize(data, bot) @bot = bot @name = data['name'] @id = data['id'].to_i @description = data['description'] @icon_id = data['icon'] @rpc_origins = data['rpc_origins'] @flags = data['flags'] @owner = @bot.ensure_user(data['owner']) end # Utility function to get a application's icon URL. # @return [String, nil] the URL to the icon image (nil if no image is set). def icon_url return nil if @icon_id.nil? API.app_icon_url(@id, @icon_id) end # The inspect method is overwritten to give more useful output def inspect "<Application name=#{@name} id=#{@id}>" end end # Mixin for the attributes members and private members should have module MemberAttributes # @return [Time] when this member joined the server. attr_reader :joined_at # @return [String, nil] the nickname this member has, or nil if it has none. attr_reader :nick alias_method :nickname, :nick # @return [Array<Role>] the roles this member has. attr_reader :roles # @return [Server] the server this member is on. attr_reader :server end # Mixin to calculate resulting permissions from overrides etc. module PermissionCalculator # Checks whether this user can do the particular action, regardless of whether it has the permission defined, # through for example being the server owner or having the Manage Roles permission # @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list. # @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked. # @example Check if the bot can send messages to a specific channel in a server. # bot_profile = bot.profile.on(event.server) # can_send_messages = bot_profile.permission?(:send_messages, channel) # @return [true, false] whether or not this user has the permission. def permission?(action, channel = nil) # If the member is the server owner, it irrevocably has all permissions. return true if owner? # First, check whether the user has Manage Roles defined. # (Coincidentally, Manage Permissions is the same permission as Manage Roles, and a # Manage Permissions deny overwrite will override Manage Roles, so we can just check for # Manage Roles once and call it a day.) return true if defined_permission?(:administrator, channel) # Otherwise, defer to defined_permission defined_permission?(action, channel) end # Checks whether this user has a particular permission defined (i. e. not implicit, through for example # Manage Roles) # @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list. # @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked. # @example Check if a member has the Manage Channels permission defined in the server. # has_manage_channels = member.defined_permission?(:manage_channels) # @return [true, false] whether or not this user has the permission defined. def defined_permission?(action, channel = nil) # Get the permission the user's roles have role_permission = defined_role_permission?(action, channel) # Once we have checked the role permission, we have to check the channel overrides for the # specific user user_specific_override = permission_overwrite(action, channel, id) # Use the ID reader as members have no ID instance variable # Merge the two permissions - if an override is defined, it has to be allow, otherwise we only care about the role return role_permission unless user_specific_override user_specific_override == :allow end # Define methods for querying permissions Discordrb::Permissions::Flags.each_value do |flag| define_method "can_#{flag}?" do |channel = nil| permission? flag, channel end end alias_method :can_administrate?, :can_administrator? private def defined_role_permission?(action, channel) # For each role, check if # (1) the channel explicitly allows or permits an action for the role and # (2) if the user is allowed to do the action if the channel doesn't specify @roles.reduce(false) do |can_act, role| # Get the override defined for the role on the channel channel_allow = permission_overwrite(action, channel, role.id) can_act = if channel_allow # If the channel has an override, check whether it is an allow - if yes, # the user can act, if not, it can't channel_allow == :allow else # Otherwise defer to the role role.permissions.instance_variable_get("@#{action}") || can_act end can_act end end def permission_overwrite(action, channel, id) # If no overwrites are defined, or no channel is set, no overwrite will be present return nil unless channel && channel.permission_overwrites[id] # Otherwise, check the allow and deny objects allow = channel.permission_overwrites[id].allow deny = channel.permission_overwrites[id].deny if allow.instance_variable_get("@#{action}") :allow elsif deny.instance_variable_get("@#{action}") :deny end # If there's no variable defined, nil will implicitly be returned end end # A voice state represents the state of a member's connection to a voice channel. It includes data like the voice # channel the member is connected to and mute/deaf flags. class VoiceState # @return [Integer] the ID of the user whose voice state is represented by this object. attr_reader :user_id # @return [true, false] whether this voice state's member is muted server-wide. attr_reader :mute # @return [true, false] whether this voice state's member is deafened server-wide. attr_reader :deaf # @return [true, false] whether this voice state's member has muted themselves. attr_reader :self_mute # @return [true, false] whether this voice state's member has deafened themselves. attr_reader :self_deaf # @return [Channel] the voice channel this voice state's member is in. attr_reader :voice_channel # @!visibility private def initialize(user_id) @user_id = user_id end # Update this voice state with new data from Discord # @note For internal use only. # @!visibility private def update(channel, mute, deaf, self_mute, self_deaf) @voice_channel = channel @mute = mute @deaf = deaf @self_mute = self_mute @self_deaf = self_deaf end end # A presence represents a # A member is a user on a server. It differs from regular users in that it has roles, voice statuses and things like # that. class Member < DelegateClass(User) # @return [true, false] whether this member is muted server-wide. def mute voice_state_attribute(:mute) end # @return [true, false] whether this member is deafened server-wide. def deaf voice_state_attribute(:deaf) end # @return [true, false] whether this member has muted themselves. def self_mute voice_state_attribute(:self_mute) end # @return [true, false] whether this member has deafened themselves. def self_deaf voice_state_attribute(:self_deaf) end # @return [Channel] the voice channel this member is in. def voice_channel voice_state_attribute(:voice_channel) end alias_method :muted?, :mute alias_method :deafened?, :deaf alias_method :self_muted?, :self_mute alias_method :self_deafened?, :self_deaf include MemberAttributes # @!visibility private def initialize(data, server, bot) @bot = bot @user = bot.ensure_user(data['user']) super @user # Initialize the delegate class # Somehow, Discord doesn't send the server ID in the standard member format... raise ArgumentError, 'Cannot create a member without any information about the server!' if server.nil? && data['guild_id'].nil? @server = server || bot.server(data['guild_id'].to_i) # Initialize the roles by getting the roles from the server one-by-one update_roles(data['roles']) @nick = data['nick'] @joined_at = data['joined_at'] ? Time.parse(data['joined_at']) : nil end # @return [true, false] whether this member is the server owner. def owner? @server.owner == self end # @param role [Role, Integer, #resolve_id] the role to check or its ID. # @return [true, false] whether this member has the specified role. def role?(role) role = role.resolve_id @roles.any? { |e| e.id == role } end # Bulk sets a member's roles. # @param role [Role, Array<Role>] The role(s) to set. def roles=(role) role_ids = role_id_array(role) API::Server.update_member(@bot.token, @server.id, @user.id, roles: role_ids) end # Adds and removes roles from a member. # @param add [Role, Array<Role>] The role(s) to add. # @param remove [Role, Array<Role>] The role(s) to remove. # @example Remove the 'Member' role from a user, and add the 'Muted' role to them. # to_add = server.roles.find {|role| role.name == 'Muted'} # to_remove = server.roles.find {|role| role.name == 'Member'} # member.modify_roles(to_add, to_remove) def modify_roles(add, remove) add_role_ids = role_id_array(add) remove_role_ids = role_id_array(remove) old_role_ids = @roles.map(&:id) new_role_ids = (old_role_ids - remove_role_ids + add_role_ids).uniq API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids) end # Adds one or more roles to this member. # @param role [Role, Array<Role>] The role(s) to add. def add_role(role) role_ids = role_id_array(role) old_role_ids = @roles.map(&:id) new_role_ids = (old_role_ids + role_ids).uniq API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids) end # Removes one or more roles from this member. # @param role [Role, Array<Role>] The role(s) to remove. def remove_role(role) old_role_ids = @roles.map(&:id) role_ids = role_id_array(role) new_role_ids = old_role_ids.reject { |i| role_ids.include?(i) } API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids) end # Server deafens this member. def server_deafen API::Server.update_member(@bot.token, @server.id, @user.id, deaf: true) end # Server undeafens this member. def server_undeafen API::Server.update_member(@bot.token, @server.id, @user.id, deaf: false) end # Server mutes this member. def server_mute API::Server.update_member(@bot.token, @server.id, @user.id, mute: true) end # Server unmutes this member. def server_unmute API::Server.update_member(@bot.token, @server.id, @user.id, mute: false) end # Sets or resets this member's nickname. Requires the Change Nickname permission for the bot itself and Manage # Nicknames for other users. # @param nick [String, nil] The string to set the nickname to, or nil if it should be reset. def nick=(nick) # Discord uses the empty string to signify 'no nickname' so we convert nil into that nick ||= '' if @user.current_bot? API::User.change_own_nickname(@bot.token, @server.id, nick) else API::Server.update_member(@bot.token, @server.id, @user.id, nick: nick) end end alias_method :nickname=, :nick= # @return [String] the name the user displays as (nickname if they have one, username otherwise) def display_name nickname || username end # Update this member's roles # @note For internal use only. # @!visibility private def update_roles(roles) @roles = roles.map do |role| role.is_a?(Role) ? role : @server.role(role.to_i) end end # Update this member's nick # @note For internal use only. # @!visibility private def update_nick(nick) @nick = nick end include PermissionCalculator # Overwriting inspect for debug purposes def inspect "<Member user=#{@user.inspect} server=#{@server.inspect} joined_at=#{@joined_at} roles=#{@roles.inspect} voice_channel=#{@voice_channel.inspect} mute=#{@mute} deaf=#{@deaf} self_mute=#{@self_mute} self_deaf=#{@self_deaf}>" end private # Utility method to get a list of role IDs from one role or an array of roles def role_id_array(role) if role.is_a? Array role.map(&:resolve_id) else [role.resolve_id] end end # Utility method to get data out of this member's voice state def voice_state_attribute(name) voice_state = @server.voice_states[@user.id] voice_state.send name if voice_state end end # Recipients are members on private channels - they exist for completeness purposes, but all # the attributes will be empty. class Recipient < DelegateClass(User) include MemberAttributes # @return [Channel] the private channel this recipient is the recipient of. attr_reader :channel # @!visibility private def initialize(user, channel, bot) @bot = bot @channel = channel raise ArgumentError, 'Tried to create a recipient for a public channel!' unless @channel.private? @user = user super @user # Member attributes @mute = @deaf = @self_mute = @self_deaf = false @voice_channel = nil @server = nil @roles = [] @joined_at = @channel.creation_time end # Overwriting inspect for debug purposes def inspect "<Recipient user=#{@user.inspect} channel=#{@channel.inspect}>" end end # This class is a special variant of User that represents the bot's user profile (things like own username and the avatar). # It can be accessed using {Bot#profile}. class Profile < User def initialize(data, bot) super(data, bot) end # Whether or not the user is the bot. The Profile can only ever be the bot user, so this always returns true. # @return [true] def current_bot? true end # Sets the bot's username. # @param username [String] The new username. def username=(username) update_profile_data(username: username) end alias_method :name=, :username= # Changes the bot's avatar. # @param avatar [String, #read] A JPG file to be used as the avatar, either # something readable (e. g. File Object) or as a data URL. def avatar=(avatar) if avatar.respond_to? :read # Set the file to binary mode if supported, so we don't get problems with Windows avatar.binmode if avatar.respond_to?(:binmode) avatar_string = 'data:image/jpg;base64,' avatar_string += Base64.strict_encode64(avatar.read) update_profile_data(avatar: avatar_string) else update_profile_data(avatar: avatar) end end # Updates the cached profile data with the new one. # @note For internal use only. # @!visibility private def update_data(new_data) @username = new_data[:username] || @username @avatar_id = new_data[:avatar_id] || @avatar_id end # Sets the user status setting to Online. # @note Only usable on User accounts. def online update_profile_status_setting('online') end # Sets the user status setting to Idle. # @note Only usable on User accounts. def idle update_profile_status_setting('idle') end # Sets the user status setting to Do Not Disturb. # @note Only usable on User accounts. def dnd update_profile_status_setting('dnd') end alias_method(:busy, :dnd) # Sets the user status setting to Invisible. # @note Only usable on User accounts. def invisible update_profile_status_setting('invisible') end # The inspect method is overwritten to give more useful output def inspect "<Profile user=#{super}>" end private # Internal handler for updating the user's status setting def update_profile_status_setting(status) API::User.change_status_setting(@bot.token, status) end def update_profile_data(new_data) API::User.update_profile(@bot.token, nil, nil, new_data[:username] || @username, new_data.key?(:avatar) ? new_data[:avatar] : @avatar_id) update_data(new_data) end end # A Discord role that contains permissions and applies to certain users class Role include IDObject # @return [Permissions] this role's permissions. attr_reader :permissions # @return [String] this role's name ("new role" if it hasn't been changed) attr_reader :name # @return [true, false] whether or not this role should be displayed separately from other users attr_reader :hoist # @return [true, false] whether this role can be mentioned using a role mention attr_reader :mentionable alias_method :mentionable?, :mentionable # @return [ColourRGB] the role colour attr_reader :colour alias_method :color, :colour # @return [Integer] the position of this role in the hierarchy attr_reader :position # This class is used internally as a wrapper to a Role object that allows easy writing of permission data. class RoleWriter # @!visibility private def initialize(role, token) @role = role @token = token end # Write the specified permission data to the role, without updating the permission cache # @param bits [Integer] The packed permissions to write. def write(bits) @role.send(:packed=, bits, false) end # The inspect method is overridden, in this case to prevent the token being leaked def inspect "<RoleWriter role=#{@role} token=...>" end end # @!visibility private def initialize(data, bot, server = nil) @bot = bot @server = server @permissions = Permissions.new(data['permissions'], RoleWriter.new(self, @bot.token)) @name = data['name'] @id = data['id'].to_i @position = data['position'] @hoist = data['hoist'] @mentionable = data['mentionable'] @colour = ColourRGB.new(data['color']) end # @return [String] a string that will mention this role, if it is mentionable. def mention "<@&#{@id}>" end # @return [Array<Member>] an array of members who have this role. # @note This requests a member chunk if it hasn't for the server before, which may be slow initially def members @server.members.select { |m| m.role? role } end alias_method :users, :members # Updates the data cache from another Role object # @note For internal use only # @!visibility private def update_from(other) @permissions = other.permissions @name = other.name @hoist = other.hoist @colour = other.colour @position = other.position end # Updates the data cache from a hash containing data # @note For internal use only # @!visibility private def update_data(new_data) @name = new_data[:name] || new_data['name'] || @name @hoist = new_data['hoist'] unless new_data['hoist'].nil? @hoist = new_data[:hoist] unless new_data[:hoist].nil? @colour = new_data[:colour] || (new_data['color'] ? ColourRGB.new(new_data['color']) : @colour) end # Sets the role name to something new # @param name [String] The name that should be set def name=(name) update_role_data(name: name) end # Changes whether or not this role is displayed at the top of the user list # @param hoist [true, false] The value it should be changed to def hoist=(hoist) update_role_data(hoist: hoist) end # Changes whether or not this role can be mentioned # @param mentionable [true, false] The value it should be changed to def mentionable=(mentionable) update_role_data(mentionable: mentionable) end # Sets the role colour to something new # @param colour [ColourRGB] The new colour def colour=(colour) update_role_data(colour: colour) end alias_method :color=, :colour= # Changes this role's permissions to a fixed bitfield. This allows setting multiple permissions at once with just # one API call. # # Information on how this bitfield is structured can be found at # https://discordapp.com/developers/docs/topics/permissions. # @example Remove all permissions from a role # role.packed = 0 # @param packed [Integer] A bitfield with the desired permissions value. # @param update_perms [true, false] Whether the internal data should also be updated. This should always be true # when calling externally. def packed=(packed, update_perms = true) update_role_data(permissions: packed) @permissions.bits = packed if update_perms end # Deletes this role. This cannot be undone without recreating the role! def delete API::Server.delete_role(@bot.token, @server.id, @id) @server.delete_role(@id) end # The inspect method is overwritten to give more useful output def inspect "<Role name=#{@name} permissions=#{@permissions.inspect} hoist=#{@hoist} colour=#{@colour.inspect} server=#{@server.inspect}>" end private def update_role_data(new_data) API::Server.update_role(@bot.token, @server.id, @id, new_data[:name] || @name, (new_data[:colour] || @colour).combined, new_data[:hoist].nil? ? @hoist : new_data[:hoist], new_data[:mentionable].nil? ? @mentionable : new_data[:mentionable], new_data[:permissions] || @permissions.bits) update_data(new_data) end end # A channel referenced by an invite. It has less data than regular channels, so it's a separate class class InviteChannel include IDObject # @return [String] this channel's name. attr_reader :name # @return [Integer] this channel's type (0: text, 1: private, 2: voice, 3: group). attr_reader :type # @!visibility private def initialize(data, bot) @bot = bot @id = data['id'].to_i @name = data['name'] @type = data['type'] end end # A server referenced to by an invite class InviteServer include IDObject # @return [String] this server's name. attr_reader :name # @return [String, nil] the hash of the server's invite splash screen (for partnered servers) or nil if none is # present attr_reader :splash_hash # @!visibility private def initialize(data, bot) @bot = bot @id = data['id'].to_i @name = data['name'] @splash_hash = data['splash_hash'] end end # A Discord invite to a channel class Invite # @return [InviteChannel] the channel this invite references. attr_reader :channel # @return [InviteServer] the server this invite references. attr_reader :server # @return [Integer] the amount of uses left on this invite. attr_reader :uses alias_method :max_uses, :uses # @return [User, nil] the user that made this invite. May also be nil if the user can't be determined. attr_reader :inviter alias_method :user, :inviter # @return [true, false] whether or not this invite is temporary. attr_reader :temporary alias_method :temporary?, :temporary # @return [true, false] whether this invite is still valid. attr_reader :revoked alias_method :revoked?, :revoked # @return [String] this invite's code attr_reader :code # @!visibility private def initialize(data, bot) @bot = bot @channel = InviteChannel.new(data['channel'], bot) @server = InviteServer.new(data['guild'], bot) @uses = data['uses'] @inviter = data['inviter'] ? (@bot.user(data['inviter']['id'].to_i) || User.new(data['inviter'], bot)) : nil @temporary = data['temporary'] @revoked = data['revoked'] @code = data['code'] end # Code based comparison def ==(other) other.respond_to?(:code) ? (@code == other.code) : (@code == other) end # Deletes this invite def delete API::Invite.delete(@bot.token, @code) end alias_method :revoke, :delete # The inspect method is overwritten to give more useful output def inspect "<Invite code=#{@code} channel=#{@channel} uses=#{@uses} temporary=#{@temporary} revoked=#{@revoked}>" end # Creates an invite URL. def url "https://discord.gg/#{@code}" end end # A Discord channel, including data like the topic class Channel include IDObject # @return [String] this channel's name. attr_reader :name # @return [Server, nil] the server this channel is on. If this channel is a PM channel, it will be nil. attr_reader :server # @return [Integer] the type of this channel (0: text, 1: private, 2: voice, 3: group) attr_reader :type # @return [Integer, nil] the id of the owner of the group channel or nil if this is not a group channel. attr_reader :owner_id # @return [Array<Recipient>, nil] the array of recipients of the private messages, or nil if this is not a Private channel attr_reader :recipients # @return [String] the channel's topic attr_reader :topic # @return [Integer] the bitrate (in bps) of the channel attr_reader :bitrate # @return [Integer] the amount of users that can be in the channel. `0` means it is unlimited. attr_reader :user_limit alias_method :limit, :user_limit # @return [Integer] the channel's position on the channel list attr_reader :position # This channel's permission overwrites, represented as a hash of role/user ID to an OpenStruct which has the # `allow` and `deny` properties which are {Permissions} objects respectively. # @return [Hash<Integer => OpenStruct>] the channel's permission overwrites attr_reader :permission_overwrites alias_method :overwrites, :permission_overwrites # @return [true, false] whether or not this channel is a PM or group channel. def private? pm? || group? end # @return [String] a string that will mention the channel as a clickable link on Discord. def mention "<##{@id}>" end # @return [Recipient, nil] the recipient of the private messages, or nil if this is not a PM channel def recipient @recipients.first if pm? end # @!visibility private def initialize(data, bot, server = nil) @bot = bot # data is a sometimes a Hash and other times an array of Hashes, you only want the last one if it's an array data = data[-1] if data.is_a?(Array) @id = data['id'].to_i @type = data['type'] || 0 @topic = data['topic'] @bitrate = data['bitrate'] @user_limit = data['user_limit'] @position = data['position'] if private? @recipients = [] if data['recipients'] data['recipients'].each do |recipient| recipient_user = bot.ensure_user(recipient) @recipients << Recipient.new(recipient_user, self, bot) end end if pm? @name = @recipients.first.username else @name = data['name'] @owner_id = data['owner_id'] end else @name = data['name'] @server = if server server else bot.server(data['guild_id'].to_i) end end # Populate permission overwrites @permission_overwrites = {} return unless data['permission_overwrites'] data['permission_overwrites'].each do |element| role_id = element['id'].to_i deny = Permissions.new(element['deny']) allow = Permissions.new(element['allow']) @permission_overwrites[role_id] = OpenStruct.new @permission_overwrites[role_id].deny = deny @permission_overwrites[role_id].allow = allow end end # @return [true, false] whether or not this channel is a text channel def text? @type.zero? end # @return [true, false] whether or not this channel is a PM channel. def pm? @type == 1 end # @return [true, false] whether or not this channel is a voice channel. def voice? @type == 2 end # @return [true, false] whether or not this channel is a group channel. def group? @type == 3 end # Sends a message to this channel. # @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error. # @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech. # @param embed [Hash, Discordrb::Webhooks::Embed, nil] The rich embed to append to this message. # @return [Message] the message that was sent. def send_message(content, tts = false, embed = nil) @bot.send_message(@id, content, tts, embed) end alias_method :send, :send_message # Sends a temporary message to this channel. # @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error. # @param timeout [Float] The amount of time in seconds after which the message sent will be deleted. # @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech. # @param embed [Hash, Discordrb::Webhooks::Embed, nil] The rich embed to append to this message. def send_temporary_message(content, timeout, tts = false, embed = nil) @bot.send_temporary_message(@id, content, timeout, tts, embed) end # Convenience method to send a message with an embed. # @example Send a message with an embed # channel.send_embed do |embed| # embed.title = 'The Ruby logo' # embed.image = Discordrb::Webhooks::EmbedImage.new(url: 'https://www.ruby-lang.org/images/header-ruby-logo.png') # end # @param message [String] The message that should be sent along with the embed. If this is the empty string, only the embed will be shown. # @param embed [Discordrb::Webhooks::Embed, nil] The embed to start the building process with, or nil if one should be created anew. # @yield [embed] Yields the embed to allow for easy building inside a block. # @yieldparam embed [Discordrb::Webhooks::Embed] The embed from the parameters, or a new one. # @return [Message] The resulting message. def send_embed(message = '', embed = nil) embed ||= Discordrb::Webhooks::Embed.new yield(embed) if block_given? send_message(message, false, embed) end # Sends multiple messages to a channel # @param content [Array<String>] The messages to send. def send_multiple(content) content.each { |e| send_message(e) } end # Splits a message into chunks whose length is at most the Discord character limit, then sends them individually. # Useful for sending long messages, but be wary of rate limits! def split_send(content) send_multiple(Discordrb.split_message(content)) end # Sends a file to this channel. If it is an image, it will be embedded. # @param file [File] The file to send. There's no clear size limit for this, you'll have to attempt it for yourself (most non-image files are fine, large images may fail to embed) # @param caption [string] The caption for the file. # @param tts [true, false] Whether or not this file's caption should be sent using Discord text-to-speech. def send_file(file, caption: nil, tts: false) @bot.send_file(@id, file, caption: caption, tts: tts) end # Deletes a message on this channel. Mostly useful in case a message needs to be deleted when only the ID is known # @param message [Message, String, Integer, #resolve_id] The message that should be deleted. def delete_message(message) API::Channel.delete_message(@bot.token, @id, message.resolve_id) end # Permanently deletes this channel def delete API::Channel.delete(@bot.token, @id) end # Sets this channel's name. The name must be alphanumeric with dashes, unless this is a voice channel (then there are no limitations) # @param name [String] The new name. def name=(name) @name = name update_channel_data end # Sets this channel's topic. # @param topic [String] The new topic. def topic=(topic) raise 'Tried to set topic on voice channel' if voice? @topic = topic update_channel_data end # Sets this channel's bitrate. # @param bitrate [Integer] The new bitrate (in bps). Number has to be between 8000-96000 (128000 for VIP servers) def bitrate=(bitrate) raise 'Tried to set bitrate on text channel' if text? @bitrate = bitrate update_channel_data end # Sets this channel's user limit. # @param limit [Integer] The new user limit. `0` for unlimited, has to be a number between 0-99 def user_limit=(limit) raise 'Tried to set user_limit on text channel' if text? @user_limit = limit update_channel_data end alias_method :limit=, :user_limit= # Sets this channel's position in the list. # @param position [Integer] The new position. def position=(position) @position = position update_channel_data end # Defines a permission overwrite for this channel that sets the specified thing to the specified allow and deny # permission sets, or change an existing one. # @param thing [User, Role] What to define an overwrite for. # @param allow [#bits, Permissions, Integer] The permission sets that should receive an `allow` override (i. e. a # green checkmark on Discord) # @param deny [#bits, Permissions, Integer] The permission sets that should receive a `deny` override (i. e. a red # cross on Discord) # @example Define a permission overwrite for a user that can then mention everyone and use TTS, but not create any invites # allow = Discordrb::Permissions.new # allow.can_mention_everyone = true # allow.can_send_tts_messages = true # # deny = Discordrb::Permissions.new # deny.can_create_instant_invite = true # # channel.define_overwrite(user, allow, deny) def define_overwrite(thing, allow, deny) allow_bits = allow.respond_to?(:bits) ? allow.bits : allow deny_bits = deny.respond_to?(:bits) ? deny.bits : deny type = if thing.is_a?(User) || thing.is_a?(Member) || thing.is_a?(Recipient) || thing.is_a?(Profile) :member elsif thing.is_a? Role :role else raise ArgumentError, '`thing` in define_overwrite needs to be a kind of User (User, Member, Recipient, Profile) or a Role!' end API::Channel.update_permission(@bot.token, @id, thing.id, allow_bits, deny_bits, type) end # Deletes a permission overwrite for this channel # @param target [Member, User, Role, Profile, Recipient, #resolve_id] What permission overwrite to delete def delete_overwrite(target) raise 'Tried deleting a overwrite for an invalid target' unless target.is_a?(Member) || target.is_a?(User) || target.is_a?(Role) || target.is_a?(Profile) || target.is_a?(Recipient) || target.respond_to?(:resolve_id) API::Channel.delete_permission(@bot.token, @id, target.resolve_id) end # Updates the cached data from another channel. # @note For internal use only # @!visibility private def update_from(other) @topic = other.topic @name = other.name @position = other.position @topic = other.topic @recipients = other.recipients @bitrate = other.bitrate @user_limit = other.user_limit @permission_overwrites = other.permission_overwrites end # The list of users currently in this channel. For a voice channel, it will return all the members currently # in that channel. For a text channel, it will return all online members that have permission to read it. # @return [Array<Member>] the users in this channel def users if text? @server.online_members(include_idle: true).select { |u| u.can_read_messages? self } elsif voice? @server.voice_states.map { |id, voice_state| @server.member(id) if !voice_state.voice_channel.nil? && voice_state.voice_channel.id == @id }.compact end end # Retrieves some of this channel's message history. # @param amount [Integer] How many messages to retrieve. This must be less than or equal to 100, if it is higher # than 100 it will be treated as 100 on Discord's side. # @param before_id [Integer] The ID of the most recent message the retrieval should start at, or nil if it should # start at the current message. # @param after_id [Integer] The ID of the oldest message the retrieval should start at, or nil if it should start # as soon as possible with the specified amount. # @example Count the number of messages in the last 50 messages that contain the letter 'e'. # message_count = channel.history(50).count {|message| message.content.include? "e"} # @return [Array<Message>] the retrieved messages. def history(amount, before_id = nil, after_id = nil, around_id = nil) logs = API::Channel.messages(@bot.token, @id, amount, before_id, after_id, around_id) JSON.parse(logs).map { |message| Message.new(message, @bot) } end # Retrieves message history, but only message IDs for use with prune # @note For internal use only # @!visibility private def history_ids(amount, before_id = nil, after_id = nil) logs = API::Channel.messages(@bot.token, @id, amount, before_id, after_id) JSON.parse(logs).map { |message| message['id'].to_i } end # Returns a single message from this channel's history by ID. # @param message_id [Integer] The ID of the message to retrieve. # @return [Message] the retrieved message. def load_message(message_id) response = API::Channel.message(@bot.token, @id, message_id) return Message.new(JSON.parse(response), @bot) rescue RestClient::ResourceNotFound return nil end alias_method :message, :load_message # Requests all pinned messages of a channel. # @return [Array<Message>] the received messages. def pins msgs = API::Channel.pinned_messages(@bot.token, @id) JSON.parse(msgs).map { |msg| Message.new(msg, @bot) } end # Delete the last N messages on this channel. # @param amount [Integer] How many messages to delete. Must be a value between 2 and 100 (Discord limitation) # @param strict [true, false] Whether an error should be raised when a message is reached that is too old to be bulk # deleted. If this is false only a warning message will be output to the console. # @raise [ArgumentError] if the amount of messages is not a value between 2 and 100 def prune(amount, strict = false) raise ArgumentError, 'Can only prune between 2 and 100 messages!' unless amount.between?(2, 100) messages = history_ids(amount) bulk_delete(messages, strict) end # Deletes a collection of messages # @param messages [Array<Message, Integer>] the messages (or message IDs) to delete. Total must be an amount between 2 and 100 (Discord limitation) # @param strict [true, false] Whether an error should be raised when a message is reached that is too old to be bulk # deleted. If this is false only a warning message will be output to the console. # @raise [ArgumentError] if the amount of messages is not a value between 2 and 100 def delete_messages(messages, strict = false) raise ArgumentError, 'Can only delete between 2 and 100 messages!' unless messages.count.between?(2, 100) messages.map!(&:resolve_id) bulk_delete(messages, strict) end # Updates the cached permission overwrites # @note For internal use only # @!visibility private def update_overwrites(overwrites) @permission_overwrites = overwrites end # Add an {Await} for a message in this channel. This is identical in functionality to adding a # {Discordrb::Events::MessageEvent} await with the `in` attribute as this channel. # @see Bot#add_await def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { in: @id }.merge(attributes), &block) end # Creates a new invite to this channel. # @param max_age [Integer] How many seconds this invite should last. # @param max_uses [Integer] How many times this invite should be able to be used. # @param temporary [true, false] Whether membership should be temporary (kicked after going offline). # @return [Invite] the created invite. def make_invite(max_age = 0, max_uses = 0, temporary = false) response = API::Channel.create_invite(@bot.token, @id, max_age, max_uses, temporary) Invite.new(JSON.parse(response), @bot) end alias_method :invite, :make_invite # Starts typing, which displays the typing indicator on the client for five seconds. # If you want to keep typing you'll have to resend this every five seconds. (An abstraction # for this will eventually be coming) def start_typing API::Channel.start_typing(@bot.token, @id) end # Creates a Group channel # @param user_ids [Array<Integer>] Array of user IDs to add to the new group channel (Excluding # the recipient of the PM channel). # @return [Channel] the created channel. def create_group(user_ids) raise 'Attempted to create group channel on a non-pm channel!' unless pm? response = API::Channel.create_group(@bot.token, @id, user_ids.shift) channel = Channel.new(JSON.parse(response), @bot) channel.add_group_users(user_ids) end # Adds a user to a Group channel # @param user_ids [Array<#resolve_id>, #resolve_id] User ID or array of user IDs to add to the group channel. # @return [Channel] the group channel. def add_group_users(user_ids) raise 'Attempted to add a user to a non-group channel!' unless group? user_ids = [user_ids] unless user_ids.is_a? Array user_ids.each do |user_id| API::Channel.add_group_user(@bot.token, @id, user_id.resolve_id) end self end alias_method :add_group_user, :add_group_users # Removes a user from a group channel. # @param user_ids [Array<#resolve_id>, #resolve_id] User ID or array of user IDs to remove from the group channel. # @return [Channel] the group channel. def remove_group_users(user_ids) raise 'Attempted to remove a user from a non-group channel!' unless group? user_ids = [user_ids] unless user_ids.is_a? Array user_ids.each do |user_id| API::Channel.remove_group_user(@bot.token, @id, user_id.resolve_id) end self end alias_method :remove_group_user, :remove_group_users # Leaves the group def leave_group raise 'Attempted to leave a non-group channel!' unless group? API::Channel.leave_group(@bot.token, @id) end alias_method :leave, :leave_group # The inspect method is overwritten to give more useful output def inspect "<Channel name=#{@name} id=#{@id} topic=\"#{@topic}\" type=#{@type} position=#{@position} server=#{@server}>" end # Adds a recipient to a group channel. # @param recipient [Recipient] the recipient to add to the group # @raise [ArgumentError] if tried to add a non-recipient # @note For internal use only # @!visibility private def add_recipient(recipient) raise 'Tried to add recipient to a non-group channel' unless group? raise ArgumentError, 'Tried to add a non-recipient to a group' unless recipient.is_a?(Recipient) @recipients << recipient end # Removes a recipient from a group channel. # @param recipient [Recipient] the recipient to remove from the group # @raise [ArgumentError] if tried to remove a non-recipient # @note For internal use only # @!visibility private def remove_recipient(recipient) raise 'Tried to remove recipient from a non-group channel' unless group? raise ArgumentError, 'Tried to remove a non-recipient from a group' unless recipient.is_a?(Recipient) @recipients.delete(recipient) end private # For bulk_delete checking TWO_WEEKS = 86_400 * 14 # Deletes a list of messages on this channel using bulk delete def bulk_delete(ids, strict = false) min_snowflake = IDObject.synthesise(Time.now - TWO_WEEKS) ids.reject! do |e| next unless e < min_snowflake message = "Attempted to bulk_delete message #{e} which is too old (min = #{min_snowflake})" raise ArgumentError, message if strict Discordrb::LOGGER.warn(message) false end API::Channel.bulk_delete_messages(@bot.token, @id, ids) end def update_channel_data API::Channel.update(@bot.token, @id, @name, @topic, @position, @bitrate, @user_limit) end end # An Embed object that is contained in a message # A freshly generated embed object will not appear in a message object # unless grabbed from its ID in a channel. class Embed # @return [Message] the message this embed object is contained in. attr_reader :message # @return [String] the URL this embed object is based on. attr_reader :url # @return [String, nil] the title of the embed object. `nil` if there is not a title attr_reader :title # @return [String, nil] the description of the embed object. `nil` if there is not a description attr_reader :description # @return [Symbol] the type of the embed object. Possible types are: # # * `:link` # * `:video` # * `:image` attr_reader :type # @return [EmbedProvider, nil] the provider of the embed object. `nil` is there is not a provider attr_reader :provider # @return [EmbedThumbnail, nil] the thumbnail of the embed object. `nil` is there is not a thumbnail attr_reader :thumbnail # @return [EmbedAuthor, nil] the author of the embed object. `nil` is there is not an author attr_reader :author # @!visibility private def initialize(data, message) @message = message @url = data['url'] @title = data['title'] @type = data['type'].to_sym @description = data['description'] @provider = data['provider'].nil? ? nil : EmbedProvider.new(data['provider'], self) @thumbnail = data['thumbnail'].nil? ? nil : EmbedThumbnail.new(data['thumbnail'], self) @author = data['author'].nil? ? nil : EmbedAuthor.new(data['author'], self) end end # An Embed thumbnail for the embed object class EmbedThumbnail # @return [Embed] the embed object this is based on. attr_reader :embed # @return [String] the CDN URL this thumbnail can be downloaded at. attr_reader :url # @return [String] the thumbnail's proxy URL - I'm not sure what exactly this does, but I think it has something to # do with CDNs attr_reader :proxy_url # @return [Integer] the width of this thumbnail file, in pixels. attr_reader :width # @return [Integer] the height of this thumbnail file, in pixels. attr_reader :height # @!visibility private def initialize(data, embed) @embed = embed @url = data['url'] @proxy_url = data['proxy_url'] @width = data['width'] @height = data['height'] end end # An Embed provider for the embed object class EmbedProvider # @return [Embed] the embed object this is based on. attr_reader :embed # @return [String] the provider's name. attr_reader :name # @return [String, nil] the URL of the provider. `nil` is there is no URL attr_reader :url # @!visibility private def initialize(data, embed) @embed = embed @name = data['name'] @url = data['url'] end end # An Embed author for the embed object class EmbedAuthor # @return [Embed] the embed object this is based on. attr_reader :embed # @return [String] the author's name. attr_reader :name # @return [String, nil] the URL of the author's website. `nil` is there is no URL attr_reader :url # @!visibility private def initialize(data, embed) @embed = embed @name = data['name'] @url = data['url'] end end # An attachment to a message class Attachment include IDObject # @return [Message] the message this attachment belongs to. attr_reader :message # @return [String] the CDN URL this attachment can be downloaded at. attr_reader :url # @return [String] the attachment's proxy URL - I'm not sure what exactly this does, but I think it has something to # do with CDNs attr_reader :proxy_url # @return [String] the attachment's filename. attr_reader :filename # @return [Integer] the attachment's file size in bytes. attr_reader :size # @return [Integer, nil] the width of an image file, in pixels, or nil if the file is not an image. attr_reader :width # @return [Integer, nil] the height of an image file, in pixels, or nil if the file is not an image. attr_reader :height # @!visibility private def initialize(data, message, bot) @bot = bot @message = message @url = data['url'] @proxy_url = data['proxy_url'] @filename = data['filename'] @size = data['size'] @width = data['width'] @height = data['height'] end # @return [true, false] whether this file is an image file. def image? !(@width.nil? || @height.nil?) end end # A message on Discord that was sent to a text channel class Message include IDObject # @return [String] the content of this message. attr_reader :content alias_method :text, :content alias_method :to_s, :content # @return [Member, User] the user that sent this message. (Will be a {Member} most of the time, it should only be a # {User} for old messages when the author has left the server since then) attr_reader :author alias_method :user, :author alias_method :writer, :author # @return [Channel] the channel in which this message was sent. attr_reader :channel # @return [Time] the timestamp at which this message was sent. attr_reader :timestamp # @return [Time] the timestamp at which this message was edited. `nil` if the message was never edited. attr_reader :edited_timestamp alias_method :edit_timestamp, :edited_timestamp # @return [Array<User>] the users that were mentioned in this message. attr_reader :mentions # @return [Array<Role>] the roles that were mentioned in this message. attr_reader :role_mentions # @return [Array<Attachment>] the files attached to this message. attr_reader :attachments # @return [Array<Embed>] the embed objects contained in this message. attr_reader :embeds # @return [Hash<String, Reaction>] the reaction objects attached to this message keyed by the name of the reaction attr_reader :reactions # @return [true, false] whether the message used Text-To-Speech (TTS) or not. attr_reader :tts alias_method :tts?, :tts # @return [String] used for validating a message was sent attr_reader :nonce # @return [true, false] whether the message was edited or not. attr_reader :edited alias_method :edited?, :edited # @return [true, false] whether the message mentioned everyone or not. attr_reader :mention_everyone alias_method :mention_everyone?, :mention_everyone alias_method :mentions_everyone?, :mention_everyone # @return [true, false] whether the message is pinned or not. attr_reader :pinned alias_method :pinned?, :pinned # @return [Integer, nil] the webhook ID that sent this message, or nil if it wasn't sent through a webhook. attr_reader :webhook_id # The discriminator that webhook user accounts have. ZERO_DISCRIM = '0000'.freeze # @!visibility private def initialize(data, bot) @bot = bot @content = data['content'] @channel = bot.channel(data['channel_id'].to_i) @pinned = data['pinned'] @tts = data['tts'] @nonce = data['nonce'] @mention_everyone = data['mention_everyone'] @author = if data['author'] if data['author']['discriminator'] == ZERO_DISCRIM # This is a webhook user! It would be pointless to try to resolve a member here, so we just create # a User and return that instead. Discordrb::LOGGER.debug("Webhook user: #{data['author']['id']}") User.new(data['author'], @bot) elsif @channel.private? # Turn the message user into a recipient - we can't use the channel recipient # directly because the bot may also send messages to the channel Recipient.new(bot.user(data['author']['id'].to_i), @channel, bot) else member = @channel.server.member(data['author']['id'].to_i) unless member Discordrb::LOGGER.debug("Member with ID #{data['author']['id']} not cached (possibly left the server).") member = @bot.user(data['author']['id'].to_i) end member end end @webhook_id = data['webhook_id'].to_i if data['webhook_id'] @timestamp = Time.parse(data['timestamp']) if data['timestamp'] @edited_timestamp = data['edited_timestamp'].nil? ? nil : Time.parse(data['edited_timestamp']) @edited = !@edited_timestamp.nil? @id = data['id'].to_i @emoji = [] @reactions = {} if data['reactions'] data['reactions'].each do |element| @reactions[element['emoji']['name']] = Reaction.new(element) end end @mentions = [] if data['mentions'] data['mentions'].each do |element| @mentions << bot.ensure_user(element) end end @role_mentions = [] # Role mentions can only happen on public servers so make sure we only parse them there if @channel.text? if data['mention_roles'] data['mention_roles'].each do |element| @role_mentions << @channel.server.role(element.to_i) end end end @attachments = [] @attachments = data['attachments'].map { |e| Attachment.new(e, self, @bot) } if data['attachments'] @embeds = [] @embeds = data['embeds'].map { |e| Embed.new(e, self) } if data['embeds'] end # Replies to this message with the specified content. # @see Channel#send_message def reply(content) @channel.send_message(content) end # Edits this message to have the specified content instead. # You can only edit your own messages. # @param new_content [String] the new content the message should have. # @param new_embed [Hash, Discordrb::Webhooks::Embed, nil] The new embed the message should have. If nil the message will be changed to have no embed. # @return [Message] the resulting message. def edit(new_content, new_embed = nil) response = API::Channel.edit_message(@bot.token, @channel.id, @id, new_content, [], new_embed ? new_embed.to_hash : nil) Message.new(JSON.parse(response), @bot) end # Deletes this message. def delete API::Channel.delete_message(@bot.token, @channel.id, @id) nil end # Pins this message def pin API::Channel.pin_message(@bot.token, @channel.id, @id) @pinned = true nil end # Unpins this message def unpin API::Channel.unpin_message(@bot.token, @channel.id, @id) @pinned = false nil end # Add an {Await} for a message with the same user and channel. # @see Bot#add_await def await(key, attributes = {}, &block) @bot.add_await(key, Discordrb::Events::MessageEvent, { from: @author.id, in: @channel.id }.merge(attributes), &block) end # @return [true, false] whether this message was sent by the current {Bot}. def from_bot? @author && @author.current_bot? end # @return [true, false] whether this message has been sent over a webhook. def webhook? !@webhook_id.nil? end # @!visibility private # @return [Array<String>] the emoji mentions found in the message def scan_for_emoji emoji = @content.split emoji = emoji.grep(/<:(?<name>\w+):(?<id>\d+)>?/) emoji end # @return [Array<Emoji>] the emotes that were used/mentioned in this message (Only returns Emoji the bot has access to, else nil). def emoji return if @content.nil? emoji = scan_for_emoji emoji.each do |element| @emoji << @bot.parse_mention(element) end @emoji end # Check if any emoji got used in this message # @return [true, false] whether or not any emoji got used def emoji? emoji = scan_for_emoji return true unless emoji.empty? end # Check if any reactions got used in this message # @return [true, false] whether or not this message has reactions def reactions? @reactions.any? end # Returns the reactions made by the current bot or user # @return [Array<Reaction>] the reactions def my_reactions @reactions.select(&:me) end # Reacts to a message # @param [String, #to_reaction] the unicode emoji, Emoji, or GlobalEmoji def create_reaction(reaction) reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction) API::Channel.create_reaction(@bot.token, @channel.id, @id, reaction) nil end alias_method :react, :create_reaction # Returns the list of users who reacted with a certain reaction # @param [String, #to_reaction] the unicode emoji, Emoji, or GlobalEmoji # @return [Array<User>] the users who used this reaction def reacted_with(reaction) reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction) response = JSON.parse(API::Channel.get_reactions(@bot.token, @channel.id, @id, reaction)) response.map { |d| User.new(d, @bot) } end # Deletes a reaction made by a user on this message # @param [User, #resolve_id] the user who used this reaction # @param [String, #to_reaction] the reaction to remove def delete_reaction(user, reaction) reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction) API::Channel.delete_user_reaction(@bot.token, @channel.id, @id, reaction, user.resolve_id) end # Delete's this clients reaction on this message # @param [String, #to_reaction] the reaction to remove def delete_own_reaction(reaction) reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction) API::Channel.delete_own_reaction(@bot.token, @channel.id, @id, reaction) end # Removes all reactions from this message def delete_all_reactions API::Channel.delete_all_reactions(@bot.token, @channel.id, @id) end # The inspect method is overwritten to give more useful output def inspect "<Message content=\"#{@content}\" id=#{@id} timestamp=#{@timestamp} author=#{@author} channel=#{@channel}>" end end # A reaction to a message class Reaction # @return [Integer] the amount of users who have reacted with this reaction attr_reader :count # @return [true, false] whether the current bot or user used this reaction attr_reader :me alias_method :me?, :me # @return [Integer] the ID of the emoji, if it was custom attr_reader :id # @return [String] the name or unicode representation of the emoji attr_reader :name def initialize(data) @count = data['count'] @me = data['me'] @id = data['emoji']['id'].nil? ? nil : data['emoji']['id'].to_i @name = data['emoji']['name'] end end # Server emoji class Emoji include IDObject # @return [String] the emoji name attr_reader :name # @return [Server] the server of this emoji attr_reader :server # @return [Array<Role>] roles this emoji is active for attr_reader :roles def initialize(data, bot, server) @bot = bot @roles = nil @name = data['name'] @server = server @id = data['id'].nil? ? nil : data['id'].to_i process_roles(data['roles']) if server end # @return [String] the layout to mention it (or have it used) in a message def mention "<:#{@name}:#{@id}>" end alias_method :use, :mention alias_method :to_s, :mention # @return [String] the layout to use this emoji in a reaction def to_reaction "#{@name}:#{@id}" end # @return [String] the icon URL of the emoji def icon_url API.emoji_icon_url(@id) end # The inspect method is overwritten to give more useful output def inspect "<Emoji name=#{@name} id=#{@id}>" end # @!visibility private def process_roles(roles) @roles = [] return unless roles roles.each do |role_id| role = server.role(role_id) @roles << role end end end # Emoji that is not tailored to a server class GlobalEmoji include IDObject # @return [String] the emoji name attr_reader :name # @return [Hash<Integer => Array<Role>>] roles this emoji is active for in every server attr_reader :role_associations def initialize(data, bot) @bot = bot @roles = nil @name = data.name @id = data.id @role_associations = Hash.new([]) @role_associations[data.server.id] = data.roles end # @return [String] the layout to mention it (or have it used) in a message def mention "<:#{@name}:#{@id}>" end alias_method :use, :mention alias_method :to_s, :mention # @return [String] the layout to use this emoji in a reaction def to_reaction "#{@name}:#{@id}" end # @return [String] the icon URL of the emoji def icon_url API.emoji_icon_url(@id) end # The inspect method is overwritten to give more useful output def inspect "<GlobalEmoji name=#{@name} id=#{@id}>" end # @!visibility private def process_roles(roles) new_roles = [] return unless roles roles.each do role = server.role(role_id) new_roles << role end new_roles end end # Basic attributes a server should have module ServerAttributes # @return [String] this server's name. attr_reader :name # @return [String] the hexadecimal ID used to identify this server's icon. attr_reader :icon_id # Utility function to get the URL for the icon image # @return [String] the URL to the icon image def icon_url return nil unless @icon_id API.icon_url(@id, @icon_id) end end # Integration Account class IntegrationAccount # @return [String] this account's name. attr_reader :name # @return [Integer] this account's ID. attr_reader :id def initialize(data) @name = data['name'] @id = data['id'].to_i end end # Server integration class Integration include IDObject # @return [String] the integration name attr_reader :name # @return [Server] the server the integration is linked to attr_reader :server # @return [User] the user the integration is linked to attr_reader :user # @return [Role, nil] the role that this integration uses for "subscribers" attr_reader :role # @return [true, false] whether emoticons are enabled attr_reader :emoticon alias_method :emoticon?, :emoticon # @return [String] the integration type (Youtube, Twitch, etc.) attr_reader :type # @return [true, false] whether the integration is enabled attr_reader :enabled # @return [true, false] whether the integration is syncing attr_reader :syncing # @return [IntegrationAccount] the integration account information attr_reader :account # @return [Time] the time the integration was synced at attr_reader :synced_at # @return [Symbol] the behaviour of expiring subscribers (:remove = Remove User from role; :kick = Kick User from server) attr_reader :expire_behaviour alias_method :expire_behavior, :expire_behaviour # @return [Integer] the grace period before subscribers expire (in days) attr_reader :expire_grace_period def initialize(data, bot, server) @bot = bot @name = data['name'] @server = server @id = data['id'].to_i @enabled = data['enabled'] @syncing = data['syncing'] @type = data['type'] @account = IntegrationAccount.new(data['account']) @synced_at = Time.parse(data['synced_at']) @expire_behaviour = [:remove, :kick][data['expire_behavior']] @expire_grace_period = data['expire_grace_period'] @user = @bot.ensure_user(data['user']) @role = server.role(data['role_id']) || nil @emoticon = data['enable_emoticons'] end # The inspect method is overwritten to give more useful output def inspect "<Integration name=#{@name} id=#{@id} type=#{@type} enabled=#{@enabled}>" end end # A server on Discord class Server include IDObject include ServerAttributes # @return [String] the region the server is on (e. g. `amsterdam`). attr_reader :region # @return [Member] The server owner. attr_reader :owner # @return [Array<Channel>] an array of all the channels (text and voice) on this server. attr_reader :channels # @return [Array<Role>] an array of all the roles created on this server. attr_reader :roles # @return [Hash<Integer, Emoji>] a hash of all the emoji available on this server. attr_reader :emoji alias_method :emojis, :emoji # @return [true, false] whether or not this server is large (members > 100). If it is, # it means the members list may be inaccurate for a couple seconds after starting up the bot. attr_reader :large alias_method :large?, :large # @return [Array<Symbol>] the features of the server (eg. "INVITE_SPLASH") attr_reader :features # @return [Integer] the absolute number of members on this server, offline or not. attr_reader :member_count # @return [Symbol] the verification level of the server (:none = none, :low = 'Must have a verified email on their Discord account', :medium = 'Has to be registered with Discord for at least 5 minutes', :high = 'Has to be a member of this server for at least 10 minutes'). attr_reader :verification_level # @return [Integer] the amount of time after which a voice user gets moved into the AFK channel, in seconds. attr_reader :afk_timeout # @return [Channel, nil] the AFK voice channel of this server, or nil if none is set attr_reader :afk_channel # @return [Hash<Integer => VoiceState>] the hash (user ID => voice state) of voice states of members on this server attr_reader :voice_states # @!visibility private def initialize(data, bot, exists = true) @bot = bot @owner_id = data['owner_id'].to_i @id = data['id'].to_i update_data(data) @large = data['large'] @member_count = data['member_count'] @verification_level = [:none, :low, :medium, :high][data['verification_level']] @splash_id = nil @embed = nil @features = data['features'].map { |element| element.downcase.to_sym } @members = {} @voice_states = {} @emoji = {} process_roles(data['roles']) process_emoji(data['emojis']) process_members(data['members']) process_presences(data['presences']) process_channels(data['channels']) process_voice_states(data['voice_states']) # Whether this server's members have been chunked (resolved using op 8 and GUILD_MEMBERS_CHUNK) yet @chunked = false @processed_chunk_members = 0 # Only get the owner of the server actually exists (i. e. not for ServerDeleteEvent) @owner = member(@owner_id) if exists end # @return [Channel] The default channel on this server (usually called #general) def default_channel @bot.channel(@id) end alias_method :general_channel, :default_channel # Gets a role on this server based on its ID. # @param id [Integer, String, #resolve_id] The role ID to look for. def role(id) id = id.resolve_id @roles.find { |e| e.id == id } end # Gets a member on this server based on user ID # @param id [Integer] The user ID to look for # @param request [true, false] Whether the member should be requested from Discord if it's not cached def member(id, request = true) id = id.resolve_id return @members[id] if member_cached?(id) return nil unless request member = @bot.member(self, id) @members[id] = member rescue nil end # @return [Array<Member>] an array of all the members on this server. def members return @members.values if @chunked @bot.debug("Members for server #{@id} not chunked yet - initiating") @bot.request_chunks(@id) sleep 0.05 until @chunked @members.values end alias_method :users, :members # @return [Array<Integration>] an array of all the integrations connected to this server. def integrations integration = JSON.parse(API::Server.integrations(@bot.token, @id)) integration.map { |element| Integration.new(element, @bot, self) } end # Cache @embed # @note For internal use only # @!visibility private def cache_embed @embed ||= JSON.parse(API::Server.resolve(@bot.token, @id))['embed_enabled'] end # @return [true, false] whether or not the server has widget enabled def embed? cache_embed if @embed.nil? @embed end # @param include_idle [true, false] Whether to count idle members as online. # @param include_bots [true, false] Whether to include bot accounts in the count. # @return [Array<Member>] an array of online members on this server. def online_members(include_idle: false, include_bots: true) @members.values.select do |e| ((include_idle ? e.idle? : false) || e.online?) && (include_bots ? true : !e.bot_account?) end end alias_method :online_users, :online_members # @return [Array<Channel>] an array of text channels on this server def text_channels @channels.select(&:text?) end # @return [Array<Channel>] an array of voice channels on this server def voice_channels @channels.select(&:voice?) end # @return [String, nil] the widget URL to the server that displays the amount of online members in a # stylish way. `nil` if the widget is not enabled. def widget_url cache_embed if @embed.nil? return nil unless @embed API.widget_url(@id) end # @param style [Symbol] The style the picture should have. Possible styles are: # * `:banner1` creates a rectangular image with the server name, member count and icon, a "Powered by Discord" message on the bottom and an arrow on the right. # * `:banner2` creates a less tall rectangular image that has the same information as `banner1`, but the Discord logo on the right - together with the arrow and separated by a diagonal separator. # * `:banner3` creates an image similar in size to `banner1`, but it has the arrow in the bottom part, next to the Discord logo and with a "Chat now" text. # * `:banner4` creates a tall, almost square, image that prominently features the Discord logo at the top and has a "Join my server" in a pill-style button on the bottom. The information about the server is in the same format as the other three `banner` styles. # * `:shield` creates a very small, long rectangle, of the style you'd find at the top of GitHub `README.md` files. It features a small version of the Discord logo at the left and the member count at the right. # @return [String, nil] the widget banner URL to the server that displays the amount of online members, # server icon and server name in a stylish way. `nil` if the widget is not enabled. def widget_banner_url(style) return nil unless @embed cache_embed if @embed.nil? API.widget_url(@id, style) end # @return [String] the hexadecimal ID used to identify this server's splash image for their VIP invite page. def splash_id @splash_id ||= JSON.parse(API::Server.resolve(@bot.token, @id))['splash'] end # @return [String, nil] the splash image URL for the server's VIP invite page. # `nil` if there is no splash image. def splash_url splash_id if @splash_id.nil? return nil unless @splash_id API.splash_url(@id, @splash_id) end # Adds a role to the role cache # @note For internal use only # @!visibility private def add_role(role) @roles << role end # Removes a role from the role cache # @note For internal use only # @!visibility private def delete_role(role_id) @roles.reject! { |r| r.id == role_id } @members.each do |_, member| new_roles = member.roles.reject { |r| r.id == role_id } member.update_roles(new_roles) end @channels.each do |channel| overwrites = channel.permission_overwrites.reject { |id, _| id == role_id } channel.update_overwrites(overwrites) end end # Adds a member to the member cache. # @note For internal use only # @!visibility private def add_member(member) @members[member.id] = member @member_count += 1 end # Removes a member from the member cache. # @note For internal use only # @!visibility private def delete_member(user_id) @members.delete(user_id) @member_count -= 1 end # Checks whether a member is cached # @note For internal use only # @!visibility private def member_cached?(user_id) @members.include?(user_id) end # Adds a member to the cache # @note For internal use only # @!visibility private def cache_member(member) @members[member.id] = member end # Updates a member's voice state # @note For internal use only # @!visibility private def update_voice_state(data) user_id = data['user_id'].to_i if data['channel_id'] unless @voice_states[user_id] # Create a new voice state for the user @voice_states[user_id] = VoiceState.new(user_id) end # Update the existing voice state (or the one we just created) channel = @channels_by_id[data['channel_id'].to_i] @voice_states[user_id].update( channel, data['mute'], data['deaf'], data['self_mute'], data['self_deaf'] ) else # The user is not in a voice channel anymore, so delete its voice state @voice_states.delete(user_id) end end # Creates a channel on this server with the given name. # @param name [String] Name of the channel to create # @param type [Integer] Type of channel to create (0: text, 2: voice) # @return [Channel] the created channel. # @raise [ArgumentError] if type is not 0 or 2 def create_channel(name, type = 0) raise ArgumentError, 'Channel type must be either 0 (text) or 2 (voice)!' unless [0, 2].include?(type) response = API::Server.create_channel(@bot.token, @id, name, type) Channel.new(JSON.parse(response), @bot) end # Creates a role on this server which can then be modified. It will be initialized (on Discord's side) # with the regular role defaults the client uses, i. e. name is "new role", permissions are the default, # colour is the default etc. # @return [Role] the created role. def create_role response = API::Server.create_role(@bot.token, @id) role = Role.new(JSON.parse(response), @bot, self) @roles << role role end # @return [Array<User>] a list of banned users on this server. def bans users = JSON.parse(API::Server.bans(@bot.token, @id)) users.map { |e| User.new(e['user'], @bot) } end # Bans a user from this server. # @param user [User, #resolve_id] The user to ban. # @param message_days [Integer] How many days worth of messages sent by the user should be deleted. def ban(user, message_days = 0) API::Server.ban_user(@bot.token, @id, user.resolve_id, message_days) end # Unbans a previously banned user from this server. # @param user [User, #resolve_id] The user to unban. def unban(user) API::Server.unban_user(@bot.token, @id, user.resolve_id) end # Kicks a user from this server. # @param user [User, #resolve_id] The user to kick. def kick(user) API::Server.remove_member(@bot.token, @id, user.resolve_id) end # Forcibly moves a user into a different voice channel. Only works if the bot has the permission needed. # @param user [User] The user to move. # @param channel [Channel] The voice channel to move into. def move(user, channel) API::Server.update_member(@bot.token, @id, user.id, channel_id: channel.id) end # Deletes this server. Be aware that this is permanent and impossible to undo, so be careful! def delete API::Server.delete(@bot.token, @id) end # Leave the server def leave API::User.leave_server(@bot.token, @id) end # Transfers server ownership to another user. # @param user [User] The user who should become the new owner. def owner=(user) API::Server.transfer_ownership(@bot.token, @id, user.id) end # Sets the server's name. # @param name [String] The new server name. def name=(name) update_server_data(name: name) end # Moves the server to another region. This will cause a voice interruption of at most a second. # @param region [String] The new region the server should be in. def region=(region) update_server_data(region: region.to_s) end # Sets the server's icon. # @param icon [String, #read] The new icon, in base64-encoded JPG format. def icon=(icon) if icon.respond_to? :read icon_string = 'data:image/jpg;base64,' icon_string += Base64.strict_encode64(icon.read) update_server_data(icon: icon_string) else update_server_data(icon: icon) end end # Sets the server's AFK channel. # @param afk_channel [Channel, nil] The new AFK channel, or `nil` if there should be none set. def afk_channel=(afk_channel) update_server_data(afk_channel_id: afk_channel.resolve_id) end # Sets the amount of time after which a user gets moved into the AFK channel. # @param afk_timeout [Integer] The AFK timeout, in seconds. def afk_timeout=(afk_timeout) update_server_data(afk_timeout: afk_timeout) end # @return [true, false] whether this server has any emoji or not. def any_emoji? @emoji.any? end alias_method :has_emoji?, :any_emoji? alias_method :emoji?, :any_emoji? # Processes a GUILD_MEMBERS_CHUNK packet, specifically the members field # @note For internal use only # @!visibility private def process_chunk(members) process_members(members) @processed_chunk_members += members.length LOGGER.debug("Processed one chunk on server #{@id} - length #{members.length}") # Don't bother with the rest of the method if it's not truly the last packet return unless @processed_chunk_members == @member_count LOGGER.debug("Finished chunking server #{@id}") # Reset everything to normal @chunked = true @processed_chunk_members = 0 end # Updates the cached data with new data # @note For internal use only # @!visibility private def update_data(new_data) @name = new_data[:name] || new_data['name'] || @name @region = new_data[:region] || new_data['region'] || @region @icon_id = new_data[:icon] || new_data['icon'] || @icon_id @afk_timeout = new_data[:afk_timeout] || new_data['afk_timeout'].to_i || @afk_timeout @afk_channel_id = new_data[:afk_channel_id] || new_data['afk_channel_id'].to_i || @afk_channel.id begin @afk_channel = @bot.channel(@afk_channel_id, self) if @afk_channel_id.nonzero? && (!@afk_channel || @afk_channel_id != @afk_channel.id) rescue Discordrb::Errors::NoPermission LOGGER.debug("AFK channel #{@afk_channel_id} on server #{@id} is unreachable, setting to nil even though one exists") @afk_channel = nil end end # Adds a channel to this server's cache # @note For internal use only # @!visibility private def add_channel(channel) @channels << channel @channels_by_id[channel.id] = channel end # Deletes a channel from this server's cache # @note For internal use only # @!visibility private def delete_channel(id) @channels.reject! { |e| e.id == id } @channels_by_id.delete(id) end # Updates the cached emoji data with new data # @note For internal use only # @!visibility private def update_emoji_data(new_data) @emoji = {} process_emoji(new_data['emojis']) end # The inspect method is overwritten to give more useful output def inspect "<Server name=#{@name} id=#{@id} large=#{@large} region=#{@region} owner=#{@owner} afk_channel_id=#{@afk_channel_id} afk_timeout=#{@afk_timeout}>" end private def update_server_data(new_data) API::Server.update(@bot.token, @id, new_data[:name] || @name, new_data[:region] || @region, new_data[:icon_id] || @icon_id, new_data[:afk_channel_id] || @afk_channel_id, new_data[:afk_timeout] || @afk_timeout) update_data(new_data) end def process_roles(roles) # Create roles @roles = [] @roles_by_id = {} return unless roles roles.each do |element| role = Role.new(element, @bot, self) @roles << role @roles_by_id[role.id] = role end end def process_emoji(emoji) return if emoji.empty? emoji.each do |element| new_emoji = Emoji.new(element, @bot, self) @emoji[new_emoji.id] = new_emoji end end def process_members(members) return unless members members.each do |element| member = Member.new(element, self, @bot) @members[member.id] = member end end def process_presences(presences) # Update user statuses with presence info return unless presences presences.each do |element| next unless element['user'] user_id = element['user']['id'].to_i user = @members[user_id] if user user.update_presence(element) else LOGGER.warn "Rogue presence update! #{element['user']['id']} on #{@id}" end end end def process_channels(channels) @channels = [] @channels_by_id = {} return unless channels channels.each do |element| channel = @bot.ensure_channel(element, self) @channels << channel @channels_by_id[channel.id] = channel end end def process_voice_states(voice_states) return unless voice_states voice_states.each do |element| update_voice_state(element) end end end # A colour (red, green and blue values). Used for role colours. If you prefer the American spelling, the alias # {ColorRGB} is also available. class ColourRGB # @return [Integer] the red part of this colour (0-255). attr_reader :red # @return [Integer] the green part of this colour (0-255). attr_reader :green # @return [Integer] the blue part of this colour (0-255). attr_reader :blue # @return [Integer] the colour's RGB values combined into one integer. attr_reader :combined # Make a new colour from the combined value. # @param combined [Integer] The colour's RGB values combined into one integer def initialize(combined) @combined = combined @red = (combined >> 16) & 0xFF @green = (combined >> 8) & 0xFF @blue = combined & 0xFF end end # Alias for the class {ColourRGB} ColorRGB = ColourRGB end