# encoding: UTF-8 # LonaCraft: personal camp-chest contents in the character cloud profile. # Shared world furniture sync still omits inventory; this module rides the # existing bank_blob / cloud_bank_storage channel as bank_json["lc_chests"], # and mirrors a plain-name snapshot into lonacraft_data["chest_by_net"]. return unless defined?(LonaCraft::Furniture) module LonaCraft module ChestCloud BOX_BASE = LonaCraft::Furniture::BOX_BASE DATA_KEY = "chest_by_net" STORY_KEY = "LonaCraftChests" class << self def cache @cache ||= {} end def reset_cache @cache = {} end def durable_store d = LonaCraft::Furniture.data rescue nil return nil if d.nil? d[DATA_KEY] = {} unless d[DATA_KEY].is_a?(Hash) d[DATA_KEY] rescue nil end def storage_record?(rec) return false unless rec.is_a?(Hash) kind = LonaCraft::Furniture.kind_for(rec['item_name']) kind && kind[:storage] rescue false end def ensure_net_id(rec) return nil unless rec.is_a?(Hash) net_id = rec['lc_net_id'] unless net_id.is_a?(String) && net_id =~ /\A[a-z0-9]{12}\.[0-9]{1,12}\z/ if defined?(LonaCraft::OnlineSync) && LonaCraft::OnlineSync.respond_to?(:furniture_id) LonaCraft::OnlineSync.furniture_id(rec) net_id = rec['lc_net_id'] else pid = 'local' begin if defined?(LonaCraft::OnlineSync) && LonaCraft::OnlineSync.respond_to?(:player_id) pid = LonaCraft::OnlineSync.player_id.to_s end rescue pid = 'local' end pid = 'local' if pid.to_s == '' net_id = "#{pid}.#{rec['uid'].to_i}" rec['lc_net_id'] = net_id end end net_id.to_s rescue nil end def box_entries(box_id) return [] if $game_boxes.nil? || box_id.to_i < BOX_BASE if defined?(WebSocket) && WebSocket.respond_to?(:_live_sync_collect_storage_box) payload = WebSocket._live_sync_collect_storage_box(box_id.to_i) entries = payload.is_a?(Hash) ? payload['entries'] : nil return entries if entries.is_a?(Array) end box = $game_boxes.get_box(box_id.to_i) rescue nil box = $game_boxes.box(box_id.to_i) if box.nil? && $game_boxes.respond_to?(:box) return [] unless box.is_a?(Hash) out = [] box.each do |item, amount| qty = amount.to_i rescue 0 next if qty <= 0 || item.nil? kind = 'item' begin kind = 'weapon' if defined?(RPG::Weapon) && item.is_a?(RPG::Weapon) kind = 'armor' if defined?(RPG::Armor) && item.is_a?(RPG::Armor) rescue end item_id = item.respond_to?(:id) ? item.id.to_i : 0 name = '' begin name = item.item_name.to_s if item.respond_to?(:item_name) rescue name = '' end next if item_id <= 0 && name == '' out << { 'kind' => kind, 'id' => item_id, 'name' => name, 'amount' => qty } end out rescue [] end def row_for(net_id, item_name, entries) { 'net_id' => net_id.to_s, 'name' => item_name.to_s, 'entries' => Array(entries) } end def entries_nonempty?(entries) entries.is_a?(Array) && entries.any? { |e| e.is_a?(Hash) && e['amount'].to_i > 0 } end def story_raw_get return nil unless defined?($story_stats) && $story_stats # Prefer @data — Story_Stats#[] returns 0 for missing keys, which # breaks "empty?" checks and JSON parse. if $story_stats.respond_to?(:data) && $story_stats.data.is_a?(Hash) return $story_stats.data[STORY_KEY] end $story_stats[STORY_KEY] rescue nil end def story_raw_set(text) return false unless defined?($story_stats) && $story_stats wrote = false # Write into @data first — reliable even if []= hooks misbehave. if $story_stats.respond_to?(:data) && $story_stats.data.is_a?(Hash) $story_stats.data[STORY_KEY] = text wrote = true end # Also go through []= so autosave / quest-cloud hooks see the change. if $story_stats.respond_to?(:[]=) $story_stats[STORY_KEY] = text wrote = true end wrote rescue false end def encode_story_blob(hash) return '' unless hash.is_a?(Hash) begin if defined?(JSON) && JSON.respond_to?(:generate) text = JSON.generate(hash) return text if text.to_s != '' end rescue end # Fallback: net_id::name::kind|id|name|amt;... per line parts = [] hash.each do |nid, row| next unless row.is_a?(Hash) ents = Array(row['entries']).map { |e| next unless e.is_a?(Hash) "#{e['kind']}|#{e['id']}|#{e['name']}|#{e['amount']}" }.compact.join(';') parts << "#{nid}::#{row['name']}::#{ents}" end parts.join("\n") rescue '' end def decode_story_blob(raw) return {} if raw.nil? || raw == 0 return raw if raw.is_a?(Hash) text = raw.to_s return {} if text.strip == '' || text == '0' if defined?(JSON) && JSON.respond_to?(:parse) parsed = JSON.parse(text) rescue nil return parsed if parsed.is_a?(Hash) end # Fallback line format out = {} text.split(/\r?\n/).each do |line| next if line.to_s.strip == '' nid, name, ents = line.split('::', 3) next if nid.to_s == '' entries = [] ents.to_s.split(';').each do |chunk| kind, id, iname, amt = chunk.split('|', 4) next if kind.to_s == '' entries << { 'kind' => kind.to_s, 'id' => id.to_i, 'name' => iname.to_s, 'amount' => amt.to_i } end out[nid.to_s] = row_for(nid, name, entries) end out rescue {} end def story_blob_load decode_story_blob(story_raw_get) rescue {} end def story_blob_save(hash) story_raw_set(encode_story_blob(hash)) rescue false end def persist_story_row(net_id, row) blob = story_blob_load if row.nil? || !entries_nonempty?(row['entries']) # Do not erase a known filled chest from story on empty live reads. return false if blob[net_id].is_a?(Hash) && entries_nonempty?(blob[net_id]['entries']) blob.delete(net_id) else blob[net_id.to_s] = row end story_blob_save(blob) rescue false end # Pull cloud/story chest snapshots into cache + durable after reconnect. def rehydrate_from_story! blob = story_blob_load n = 0 blob.each do |net_id, row| next unless row.is_a?(Hash) && entries_nonempty?(row['entries']) stored = row_for(net_id, row['name'], row['entries']) cache[net_id.to_s] = stored store = durable_store store[net_id.to_s] = stored if store n += 1 end n > 0 rescue false end def remember_row(row, allow_empty = false) return false unless row.is_a?(Hash) net_id = row['net_id'].to_s return false if net_id == '' entries = row['entries'] return false unless entries.is_a?(Array) existing = cache[net_id] existing = durable_store && durable_store[net_id] if !existing.is_a?(Hash) existing = story_blob_load[net_id] if !existing.is_a?(Hash) filled = entries_nonempty?(entries) if !allow_empty && !filled && existing.is_a?(Hash) && entries_nonempty?(existing['entries']) return false end stored = row_for(net_id, row['name'], entries) store = durable_store if filled cache[net_id] = stored store[net_id] = stored if store persist_story_row(net_id, stored) elsif allow_empty cache.delete(net_id) store.delete(net_id) if store blob = story_blob_load blob.delete(net_id) story_blob_save(blob) else return false end begin prefix = net_id.split('.', 2)[0] if defined?(LonaCraft::OnlineSync) && LonaCraft::OnlineSync.respond_to?(:remember_identity) && LonaCraft::OnlineSync.respond_to?(:valid_player_id?) && LonaCraft::OnlineSync.valid_player_id?(prefix) LonaCraft::OnlineSync.remember_identity(prefix) story = LonaCraft::OnlineSync.story_get(LonaCraft::OnlineSync::STORY_ID_KEY).to_s rescue '' unless LonaCraft::OnlineSync.valid_player_id?(story) LonaCraft::OnlineSync.story_set(LonaCraft::OnlineSync::STORY_ID_KEY, prefix) d = LonaCraft::OnlineSync.data rescue nil d['lc_online_identity'] = prefix if d.is_a?(Hash) end end rescue end true rescue false end def snapshot_record(rec, allow_empty = false) return false unless storage_record?(rec) net_id = ensure_net_id(rec) return false if net_id.nil? || net_id == '' box_id = rec['box'].to_i return false if box_id < BOX_BASE remember_row(row_for(net_id, rec['item_name'], box_entries(box_id)), allow_empty) rescue false end def forget_record(rec) return false unless rec.is_a?(Hash) net_id = ensure_net_id(rec) return false if net_id.nil? || net_id == '' cache.delete(net_id) store = durable_store store.delete(net_id) if store blob = story_blob_load blob.delete(net_id) story_blob_save(blob) true rescue false end def cached_row(net_id) key = net_id.to_s return nil if key == '' row = cache[key] return row if row.is_a?(Hash) && entries_nonempty?(row['entries']) store = durable_store stored = store && store[key] if stored.is_a?(Hash) && entries_nonempty?(stored['entries']) cache[key] = stored return stored end blob = story_blob_load story_row = blob[key] if story_row.is_a?(Hash) && entries_nonempty?(story_row['entries']) cache[key] = story_row if store store[key] = story_row end return story_row end row.is_a?(Hash) ? row : nil rescue nil end def snapshot_live(include_empty = false) out = [] return out unless defined?(LonaCraft::Furniture) furn = LonaCraft::Furniture records = furn.records rescue nil return out unless records.is_a?(Array) records.each do |rec| next unless storage_record?(rec) next unless furn.local_owner?(rec) net_id = ensure_net_id(rec) next if net_id.nil? || net_id == '' box_id = rec['box'].to_i next if box_id < BOX_BASE entries = box_entries(box_id) next if entries.empty? && !include_empty row = row_for(net_id, rec['item_name'], entries) # Never let a transient empty live box erase filled durable/story rows. remember_row(row) if entries_nonempty?(entries) out << row end begin out.sort_by! { |row| [row['net_id'].to_s, row['name'].to_s] } rescue end out rescue [] end # Filled live boxes win. Cache / durable / story fill gaps (other maps, # wiped $game_boxes, cloud restore). Empty live never erases filled rows. def collect_for_bank by_id = {} [cache, durable_store, story_blob_load].each do |src| next unless src.is_a?(Hash) src.each do |net_id, row| key = net_id.to_s next if key == '' next unless row.is_a?(Hash) entries = row['entries'] next unless entries_nonempty?(entries) by_id[key] = row_for(key, row['name'], entries) end end snapshot_live(false).each do |row| next unless row.is_a?(Hash) key = row['net_id'].to_s next if key == '' next unless entries_nonempty?(row['entries']) by_id[key] = row end rows = by_id.values begin rows.sort_by! { |row| [row['net_id'].to_s, row['name'].to_s] } rescue end rows rescue [] end def remember_rows(rows) return false unless rows.is_a?(Array) rows.each { |row| remember_row(row) } true rescue false end def remember_from_bank_json(bank_json) return false unless bank_json.is_a?(Hash) remember_rows(bank_json['lc_chests']) rescue false end def resolve_entry_item(entry) return nil unless entry.is_a?(Hash) if defined?(WebSocket) && WebSocket.respond_to?(:_bootstrap_bank_entry_item) return WebSocket._bootstrap_bank_entry_item(entry) end name = entry['name'].to_s.strip if name != '' && defined?($data_ItemName) && $data_ItemName.is_a?(Hash) obj = $data_ItemName[name] return obj if obj end kind = entry['kind'].to_s.downcase item_id = entry['id'].to_i return nil if item_id <= 0 case kind when 'weapon' $data_weapons && $data_weapons[item_id] when 'armor' $data_armors && $data_armors[item_id] else $data_items && $data_items[item_id] end rescue nil end def write_entries_to_box(box_id, entries) return false if $game_boxes.nil? || box_id.to_i < BOX_BASE return false unless $game_boxes.respond_to?(:write_box) rebuilt = {} Array(entries).each do |entry| next unless entry.is_a?(Hash) qty = entry['amount'].to_i next if qty <= 0 item = resolve_entry_item(entry) next if item.nil? rebuilt[item] ||= 0 rebuilt[item] += qty end $game_boxes.write_box(box_id.to_i, rebuilt) true rescue false end def apply_to_record(rec) return false unless storage_record?(rec) return false unless LonaCraft::Furniture.local_owner?(rec) net_id = ensure_net_id(rec) return false if net_id.nil? || net_id == '' row = cached_row(net_id) return false unless row.is_a?(Hash) entries = row['entries'] return false unless entries.is_a?(Array) && !entries.empty? box_id = rec['box'].to_i if box_id < BOX_BASE box_id = LonaCraft::Furniture.next_box_id rec['box'] = box_id end # Do not clobber a non-empty live box with an older snapshot. unless LonaCraft::Furniture.box_empty?(box_id) snapshot_record(rec) return true end write_entries_to_box(box_id, entries) rescue false end def apply_all_cached! return false unless defined?(LonaCraft::Furniture) records = LonaCraft::Furniture.records rescue nil return false unless records.is_a?(Array) records.each { |rec| apply_to_record(rec) } true rescue false end def refresh_cache_from_live! snapshot_live(false) true rescue false end def lonacraft_storage_box?(box_id) box_id.to_i >= BOX_BASE rescue false end def record_for_box(box_id) bid = box_id.to_i return nil if bid < BOX_BASE records = LonaCraft::Furniture.records rescue nil return nil unless records.is_a?(Array) records.find { |rec| storage_record?(rec) && rec['box'].to_i == bid } rescue nil end def snapshot_box(box_id) rec = record_for_box(box_id) # allow_empty: player closed/moved items — intentional empty must persist. return snapshot_record(rec, true) if rec false rescue false end def request_cloud_save(box_id = nil) snapshot_box(box_id) if box_id refresh_cache_from_live! collect_for_bank if defined?(WebSocket) && WebSocket.respond_to?(:bootstrap_remember_current_bank) WebSocket.bootstrap_remember_current_bank end if defined?(MPCloudOnlySave) ok = MPCloudOnlySave.send_tracked_now('cloud_bank_storage', true) MPCloudOnlySave.request('cloud_bank_storage', 1) unless ok return true elsif defined?(MPImmediateLiveSync) MPImmediateLiveSync.trigger('bank_storage', true, false) return true end false rescue false end end end end # Persist camp chests when the player moves items / closes storage. if defined?(Scene_ItemStorage) class Scene_ItemStorage unless method_defined?(:lc_chest_cloud_move_item) alias_method :lc_chest_cloud_move_item, :move_item def move_item(val = nil) result = lc_chest_cloud_move_item(val) begin if defined?(LonaCraft::ChestCloud) && LonaCraft::ChestCloud.lonacraft_storage_box?(@box_id) LonaCraft::ChestCloud.request_cloud_save(@box_id) end rescue end result end end unless method_defined?(:lc_chest_cloud_terminate) alias_method :lc_chest_cloud_terminate, :terminate def terminate(*args, &block) begin if defined?(LonaCraft::ChestCloud) && LonaCraft::ChestCloud.lonacraft_storage_box?(@box_id) LonaCraft::ChestCloud.request_cloud_save(@box_id) end rescue end lc_chest_cloud_terminate(*args, &block) end end end end