AssetsUpdate.lua 16.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
--[[
    --新写的纯lua热更新 新特征
    --1.用户下载新版本,删除老版本的热更内容
    --2.纯lua实现,不依赖同城游引擎接口
    --3.Android和IOS上未测试过

    使用方法:
    local AssetsUpdate = require("ctkj.utils.AssetsUpdate");
    AssetsUpdate.init(updateSuccessCallback,updateProgressCallback,updateFailedCallback);
--]]

local AssetsUpdate = class("AssetsUpdate")

AssetsUpdate.VERSION_NUM = 0;    --当前安装包版本号,用于热更新
AssetsUpdate.localUpdateVersion = 0;  --本地热更版本号(热更新过后的版本号)
AssetsUpdate.newVersion = 0;    --服务器上的最新版本号


AssetsUpdate.gameid = "yxdt" --游戏名缩写
AssetsUpdate.platform = "android" --平台
AssetsUpdate.isEncrypt = 1;

AssetsUpdate.updateResList = {};
AssetsUpdate.updateResProgress = 1;

local newFilelistData = nil;
local filelistLocal = {};
local filelistServer = {};

local UPDATE_PATH_NAME = "GameUpdate/"..AssetsUpdate.gameid.."_"..CHANNEL;

function AssetsUpdate.init(updateSuccessCallback,updateProgressCallback,updateFailedCallback)
    AssetsUpdate.updateSuccessCallback,AssetsUpdate.updateProgressCallback,AssetsUpdate.updateFailedCallback = updateSuccessCallback,updateProgressCallback,updateFailedCallback;
    
    local targetPlatform = cc.Application:getInstance():getTargetPlatform();
    if targetPlatform == cc.PLATFORM_OS_IPHONE or targetPlatform == cc.PLATFORM_OS_IPAD  then
        AssetsUpdate.platform = "ios";
    elseif targetPlatform == cc.PLATFORM_OS_ANDROID then
        AssetsUpdate.platform = "android";
    elseif targetPlatform == cc.PLATFORM_OS_WINDOWS then
        AssetsUpdate.platform = "win";
        AssetsUpdate.isEncrypt = 0;
    end

    if cc.UserDefault:getInstance():getStringForKey("versionnum") ~= "" then
        AssetsUpdate.localUpdateVersion = tonumber(cc.UserDefault:getInstance():getStringForKey("versionnum"));
    else
        AssetsUpdate.localUpdateVersion = 0;
    end
    logUI("本地更新版本:"..AssetsUpdate.localUpdateVersion);

    local versionnumFullPath = cc.FileUtils:getInstance():fullPathForFilename('res/versionnum.txt');
    local versionnumStr = cc.FileUtils:getInstance():getStringFromFile(versionnumFullPath);
    local function readLine(str)
        if str ~= "" then
            AssetsUpdate.VERSION_NUM = tonumber(str);
        end
    end
    readLine(versionnumStr);
    logUI("安装包版本:"..AssetsUpdate.VERSION_NUM);
    
    AssetsUpdate.server = "http://game.topdraw.com.cn/"..AssetsUpdate.gameid.."/"..CHANNEL.."/"..AssetsUpdate.platform.."/"..DeviceUtil.getAppVersionName().."/";
    AssetsUpdate.rootPath = cc.FileUtils:getInstance():getWritablePath();
    AssetsUpdate.resPath = AssetsUpdate.rootPath..UPDATE_PATH_NAME .. "/";
    if not (cc.FileUtils:getInstance():isDirectoryExist(AssetsUpdate.resPath)) then
        cc.FileUtils:getInstance():createDirectory(AssetsUpdate.resPath);
    end

    --版本比较
    AssetsUpdate.checkVersions();
--    AssetsUpdate.timeoutID = cc.Director:getInstance():getScheduler():scheduleScriptFunc(handler(AssetsUpdate, AssetsUpdate.timeOut), 1, false); --超时处理
end

local function setSearchUpdatePath()
    --不能在判断本地版本和服务器版本之前设置搜索路径
    --因为热更本地版本是最新发布的版本,需要删除之前热更新的目录
    local searchPaths = cc.FileUtils:getInstance():getSearchPaths();
    table.insert(searchPaths,1,AssetsUpdate.resPath);
    table.insert(searchPaths,2,AssetsUpdate.resPath .. 'res/');
    table.insert(searchPaths,3,AssetsUpdate.resPath .. 'src/');
    cc.FileUtils:getInstance():setSearchPaths(searchPaths);
end

--更新本地版本号
local function setVersion()
    AssetsUpdate.newVersion = AssetsUpdate.newVersion or "1";
    cc.UserDefault:getInstance():setStringForKey("versionnum", AssetsUpdate.newVersion);
    cc.UserDefault:getInstance():flush();
end

--更新失败
local function updateFailed()
    if AssetsUpdate.localUpdateVersion > AssetsUpdate.VERSION_NUM then
        logUI("热更失败,本地热更版本大于原始包版本:"..AssetsUpdate.localUpdateVersion);
    else
        logUI("热更失败,没有热更过版本:"..AssetsUpdate.VERSION_NUM);
    end
    
    setSearchUpdatePath();
    if AssetsUpdate.updateFailedCallback then
        AssetsUpdate.updateFailedCallback();
    end
    
    if AssetsUpdate.timeoutID ~= nil then 
        cc.Director:getInstance():getScheduler():unscheduleScriptEntry(AssetsUpdate.timeoutID);
        AssetsUpdate.timeoutID = nil;
    end
end

--更新进度(需要更新的文件数量)
local function updateProgress(_count, _total, _filename)
    if AssetsUpdate.updateProgressCallback then
        AssetsUpdate.updateProgressCallback({count = _count,total = _total,filename=_filename});
    end
end

--更新完成
local function updateSuccess()
    logUI("热更新成功,热更版本号:"..AssetsUpdate.newVersion);
    setVersion();
    setSearchUpdatePath();
    if AssetsUpdate.updateSuccessCallback then
        AssetsUpdate.updateSuccessCallback();
    end

    if AssetsUpdate.timeoutID ~= nil then 
        cc.Director:getInstance():getScheduler():unscheduleScriptEntry(AssetsUpdate.timeoutID)
        AssetsUpdate.timeoutID = nil
    end
end

--版本比较
function AssetsUpdate.checkVersions()
    local xhr = cc.XMLHttpRequest:new();
    xhr.responseType = 0;   --string类型
    xhr:open("GET", AssetsUpdate.server.."version.txt");    --感觉POST方式会自动在http://后加www,由于公司热更新服务器域名没有解析www所以改成GET方式

    local scheduler = cc.Director:getInstance():getScheduler();
    AssetsUpdate.timeoutID = cc.Director:getInstance():getScheduler():scheduleScriptFunc(function ()
        xhr:unregisterScriptHandler();
        updateFailed();
    end, 5,false);

    local function onReadyStateChange() 
        if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then
            local confingArr = AssetsUpdate.string_split(xhr.response, "\n");
            if #confingArr >= 1 then
                local verArr = AssetsUpdate.string_split(confingArr[1], "=");
                AssetsUpdate.newVersion = tonumber(verArr[2]);
                logUI("localUpdateVersion:"..AssetsUpdate.localUpdateVersion.." newVersion:"..AssetsUpdate.newVersion);
                if AssetsUpdate.VERSION_NUM > AssetsUpdate.newVersion then
                    logUI("新版本,删除上个版本热更新的目录");
                    cc.FileUtils:getInstance():removeDirectory(AssetsUpdate.resPath);
                    if AssetsUpdate.updateSuccessCallback then
                        AssetsUpdate.updateSuccessCallback();
                    end
                elseif AssetsUpdate.newVersion == AssetsUpdate.localUpdateVersion or AssetsUpdate.newVersion == AssetsUpdate.VERSION_NUM then
                    logUI("版本一致不需要更新");
                    updateSuccess();
                else
                    logUI("查找需要更新的资源并下载");
                    setSearchUpdatePath();
                    AssetsUpdate.checkUpdateRes();
                end
            else
                logUI("更新失败,热更新信息格式错误:"..AssetsUpdate.server.."version.txt");
                updateFailed();
            end
        else
            logUI("更新失败,资源不存在:"..AssetsUpdate.server.."version.txt");
            logUI("删除上个版本热更新的目录");
            cc.FileUtils:getInstance():removeDirectory(AssetsUpdate.resPath);
            updateFailed();
        end
        if AssetsUpdate.timeoutID ~= nil then 
            cc.Director:getInstance():getScheduler():unscheduleScriptEntry(AssetsUpdate.timeoutID)
            AssetsUpdate.timeoutID = nil
        end
        xhr:unregisterScriptHandler();
    end
    xhr:registerScriptHandler(onReadyStateChange);
    xhr:send();
end

local function getFileList(_path,_list)
    local _str = cc.FileUtils:getInstance():getStringFromFile(_path);
    local function readLineFun(lineStr)
        local contents = StringUtil.split(lineStr,',');
        if #contents > 1 then
            _list[contents[1]] = contents[2];
        end
    end

    local index = 1;
    local function readLine(str)
        local a,b = string.find(str,"\n");
        if a then
            local lineStr = string.sub(str,1,a-1);
            readLineFun(lineStr);

            index = index + 1;
            str = string.sub(str,b+1);
            readLine(str);
        else
            readLineFun(str);
        end
    end
    readLine(_str);
end

--查找更新资源
function AssetsUpdate.checkUpdateRes()
    local fullPath = cc.FileUtils:getInstance():fullPathForFilename('filelist.txt');
    getFileList(fullPath,filelistLocal);

    local xhr = cc.XMLHttpRequest:new();
    xhr.responseType = 0;
    xhr:open("GET", AssetsUpdate.server.."update/".."filelist.txt");
    local function onReadyStateChange()   
        if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then
            newFilelistData = xhr.response;
            AssetsUpdate.writeResToLocal("filelist_temp.txt",xhr.response);
            local fullPath = AssetsUpdate.resPath .. "filelist_temp.txt";
            local file = io.open(fullPath,'r');
            if file then
                local function readServerFilelist()
                    local txt = file:read("*l")
                    if txt ~= nil then 
                        local lines = AssetsUpdate.string_split(txt, ",");
                        filelistServer[lines[1]] = lines[2];
                        return readServerFilelist()
                    end
                end
                readServerFilelist();
                io.close(file);
            else    
                print('filelist.txt read error!')
            end
            AssetsUpdate.updateResProgress = 1;
            AssetsUpdate.updateResList = AssetsUpdate.getUpdateResList();
            local len = #AssetsUpdate.updateResList;
            if len > 0 then
                updateProgress(0, len,AssetsUpdate.updateResList[1]);
            end
            AssetsUpdate.downloadRes();
        else
            logUI("更新失败,资源不存在:"..AssetsUpdate.server.."update/".."filelist.txt");
            updateFailed();
        end
    end
    xhr:registerScriptHandler(onReadyStateChange)   
    xhr:send();
end

--查找需要更新资源表(更新与新增,没考虑删除)
function AssetsUpdate.getUpdateResList()
    local addResTable = {}

    for key1, var1 in pairs(filelistServer) do
        local key = key1;
        if AssetsUpdate.isEncrypt == 1 then
            if string.sub(key1,string.len(key1)-3,string.len(key1)) == ".lua" then
                key = key1.."c";
            end
        end
        if filelistLocal[key1] then
            if var1 ~= filelistLocal[key1] and key1 ~= "res/filelist.txt" then
                table.insert(addResTable,key)
            end
        else
            table.insert(addResTable,key)
        end
    end

    return addResTable;
end

--下载更新资源
function AssetsUpdate.downloadRes()
    local fileName = AssetsUpdate.updateResList[AssetsUpdate.updateResProgress] 
    if fileName then
        local xhr = cc.XMLHttpRequest:new()    
--        xhr:open("GET", AssetsUpdate.server..AssetsUpdate.newVersion.."/"..fileName);
        xhr:open("GET", AssetsUpdate.server.."update/"..fileName);

        local function onReadyStateChange()  
            if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then
                local index = AssetsUpdate.string_lastIndexOf(fileName, "/");
                local updatePath = string.sub(fileName, 1, index);
                local file = string.sub(fileName, index + 1);
                index = AssetsUpdate.string_lastIndexOf(file, ".");
                local fileName1 = string.sub(file, 1, index - 1);
                local fileExtend1 = string.sub(file, index);

                print("下载更新资源:"..fileName1);
                local result = AssetsUpdate.writeResToLocal(updatePath..fileName1.."_temp"..fileExtend1,xhr.response);
                if result then
                    print("count:"..AssetsUpdate.updateResProgress..",name:"..fileName);
                    updateProgress(AssetsUpdate.updateResProgress, #AssetsUpdate.updateResList,fileName);
                    AssetsUpdate.updateResProgress = AssetsUpdate.updateResProgress + 1;
                    AssetsUpdate.downloadRes();
                end
            else
                logUI("更新失败,资源不存在:"..fileName);
                updateFailed();
            end
        end
        xhr:registerScriptHandler(onReadyStateChange);
        xhr:send();
    else
        print("更新完成,进入游戏");
        local req = {};
        for i,path in ipairs(AssetsUpdate.updateResList) do
            local index = AssetsUpdate.string_lastIndexOf(path, "/");
            local updatePath = string.sub(path, 1, index);
            local resname = string.sub(path, index + 1);
            index = AssetsUpdate.string_lastIndexOf(resname, ".");
            local fileName1 = string.sub(resname, 1, index - 1);
            local fileExtend1 = string.sub(resname, index);
            if cc.FileUtils:getInstance():isFileExist(AssetsUpdate.resPath ..updatePath..fileName1.."_temp"..fileExtend1) then
                cc.FileUtils:getInstance():renameFile(AssetsUpdate.resPath ..updatePath,fileName1.."_temp"..fileExtend1,fileName1..fileExtend1)
            end

            if string.find(path, "AssetsUpdate") == nil then
                for k,_ in pairs(package.loaded) do
                    k = string.gsub(k, "%.", "/")
                    local G_index = AssetsUpdate.string_lastIndexOf(path, ".")
                    local G_filename = string.sub(path, 1, G_index - 1)
                    if string.sub(k, 1, 4) ~= "src/" then 
                        k = "src/"..k
                    end
                    if k == G_filename then
                        table.insert(req, k);
                        package.loaded[k] = nil;
                    end
                end
            end
        end

--        cc.FileUtils:getInstance():purgeCachedEntries();
--        if #req > 0 then
--            for key, value in pairs(req) do
--                print("require:"..value)
--                require(value)
--            end
--        end
        for key1, var1 in pairs(filelistServer) do
            filelistLocal[key1] = var1;
        end
        local mergeFilelistData = "";   --合并服务器新的文件md5
        for i,v in pairs(filelistLocal) do
            mergeFilelistData = mergeFilelistData .. i..","..v;
        end
        print("合并服务器filelist.txt");
        AssetsUpdate.writeResToLocal("res/filelist.txt",mergeFilelistData);
        cc.FileUtils:getInstance():removeFile(AssetsUpdate.resPath .. "filelist_temp.txt");
        updateSuccess();
    end
end


--资源本地写入
function AssetsUpdate.writeResToLocal(resName, resData)
    local result = false;
    local tempResName = resName;
    local maxLength = string.len(tempResName);
    local directoryLen = 0;
    local tag = string.find(tempResName,'/');
    while tag do
        if tag ~= 1 then
            directoryLen = directoryLen + tag;
        end
        tempResName = string.sub(tempResName,tag + 1,maxLength)
        tag = string.find(tempResName,'/')
    end
    
    if directoryLen ~= 0 then
        local tmpPath = string.sub(resName,1,directoryLen);
        local fullPath = AssetsUpdate.resPath .. tmpPath;
        if not (cc.FileUtils:getInstance():isDirectoryExist(fullPath)) then         
            cc.FileUtils:getInstance():createDirectory(fullPath);
        end
    end

    local updateResPath = AssetsUpdate.resPath .. resName;
    print("资源写入本地"..updateResPath)
    local fp = io.open(updateResPath, 'w')
    if fp then
        fp:write(resData)
        io.close(fp);
        result = true;
    else
        print('downloadRes write error!!');
        updateFailed();
    end
    return result;
end

function AssetsUpdate.timeOut(dt)
    AssetsUpdate.timeOutTime = AssetsUpdate.timeOutTime or 30;
    AssetsUpdate.timeOutTime = AssetsUpdate.timeOutTime - 1;
    print("AssetsUpdate.timeOutTime:"..AssetsUpdate.timeOutTime);
    if AssetsUpdate.timeOutTime == 0 then 
        updateFailed();
    end
end

function AssetsUpdate.string_split(str, split_char)
    local sub_str_tab = {};
    while (true) do
        local pos = nil
        for i = 1, #str do
            if string.sub(str, i, i) == split_char then 
        	   pos = i
        	   break
        	end
        end
        if (not pos) then
            sub_str_tab[#sub_str_tab + 1] = str;
            break;
        end
        local sub_str = string.sub(str, 1, pos - 1);
        sub_str_tab[#sub_str_tab + 1] = sub_str;
        str = string.sub(str, pos + 1, #str);
    end

    return sub_str_tab;
end

function AssetsUpdate.string_lastIndexOf(str, split_char)
    local len = #str
    for i = len, 1, -1 do 
        if string.sub(str, i, i) == split_char then 
            return i
        end
    end

    return 0
end

return AssetsUpdate