UGCKitBGMHelper.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. // Copyright (c) 2019 Tencent. All rights reserved.
  2. #import "UGCKitBGMHelper.h"
  3. #import "pthread.h"
  4. #define BGM_GROUP @"group.com.tencent.bgm.list"
  5. // percent < 0 失败
  6. // url 为 nil 是进度
  7. typedef void(^DownLoadCallback)(float percent, NSString* url);
  8. @interface TCBGMDownloadTask : NSObject
  9. @property (strong, nonatomic) NSString *destPath;
  10. @property (copy, nonatomic) DownLoadCallback callback;
  11. @end
  12. @implementation TCBGMDownloadTask
  13. @end
  14. @interface UGCKitBGMHelper() <NSURLSessionDownloadDelegate> {
  15. NSDictionary* _configs;
  16. NSUserDefaults* _userDefaults;
  17. NSString* _userIDKey;
  18. // NSMutableDictionary* _tasks;
  19. NSURLSessionDownloadTask* _currentTask;
  20. NSURLSession *_urlSession;
  21. NSOperationQueue *_sessionDelegateQueue;
  22. TCBGMElement* _currentEle;
  23. NSString* _bgmPath;
  24. NSMutableDictionary<NSURLSessionTask *, TCBGMDownloadTask*> *_taskDictionary;
  25. }
  26. @property(nonatomic, assign)pthread_mutex_t lock;
  27. @property(nonatomic, assign)pthread_cond_t cond;
  28. @property(nonatomic, strong)dispatch_queue_t queue;
  29. @property(nonatomic)NSMutableDictionary* bgmDict;
  30. @property(nonatomic)NSMutableDictionary* bgmList;//只用来存储路径
  31. @property(nonatomic,weak) id <TCBGMHelperListener>delegate;
  32. @end
  33. @implementation UGCKitBGMHelper
  34. + (instancetype)sharedInstance {
  35. static UGCKitBGMHelper* _sharedInstance;
  36. static dispatch_once_t onceToken;
  37. dispatch_once(&onceToken, ^{
  38. _sharedInstance = [UGCKitBGMHelper new];
  39. });
  40. return _sharedInstance;
  41. }
  42. -(void) setDelegate:(nonnull id<TCBGMHelperListener>) delegate{
  43. _delegate = delegate;
  44. }
  45. -(id) init{
  46. if(self = [super init]){
  47. _taskDictionary = [[NSMutableDictionary alloc] init];
  48. _sessionDelegateQueue = [[NSOperationQueue alloc] init];
  49. _sessionDelegateQueue.underlyingQueue = dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0);
  50. _urlSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration ephemeralSessionConfiguration]
  51. delegate:self
  52. delegateQueue:_sessionDelegateQueue];
  53. // if(![[TCLoginModel sharedInstance] isLogin]){
  54. // self = nil;
  55. // return nil;
  56. // }
  57. NSFileManager *fileManager = [NSFileManager defaultManager];
  58. _bgmPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/bgm"];
  59. if(![fileManager fileExistsAtPath:_bgmPath]){
  60. if(![fileManager createDirectoryAtPath:_bgmPath withIntermediateDirectories:YES attributes:nil error:nil]){
  61. BGMLog(ASLocalizedString(@"创建BGM目录失败"));
  62. return nil;
  63. }
  64. }
  65. pthread_mutex_init(&_lock, NULL);
  66. pthread_cond_init(&_cond, NULL);
  67. _userDefaults = [[NSUserDefaults alloc] initWithSuiteName:BGM_GROUP];
  68. if (_userDefaults == nil) {
  69. _userDefaults = [NSUserDefaults standardUserDefaults];
  70. }
  71. // _tasks = [[NSMutableDictionary alloc] init];
  72. _userIDKey = @"_bgm";
  73. _queue = dispatch_queue_create("com.tencent.txcloud.videoedit.bgm.download", DISPATCH_QUEUE_SERIAL);
  74. dispatch_async(_queue, ^{[self loadLocalData];});
  75. }
  76. return self;
  77. }
  78. - (void)dealloc {
  79. pthread_mutex_destroy(&_lock);
  80. pthread_cond_destroy(&_cond);
  81. }
  82. - (void)_bgmTask:(NSString *)url {
  83. NSString* localListPath = url;
  84. __weak __typeof(self) weak = self;
  85. if([url hasPrefix:@"http"]){
  86. localListPath = [_bgmPath stringByAppendingPathComponent:@"bgm_list.json"];
  87. __block BOOL ret = false;
  88. pthread_mutex_lock(&_lock);
  89. [self downloadFile:url dstUrl:localListPath callback:^(float percent, NSString* path){
  90. __strong UGCKitBGMHelper* strong = weak;
  91. if(strong){
  92. if(percent < 0){
  93. pthread_cond_signal(&(strong->_cond));
  94. }
  95. else{
  96. if(path != nil){
  97. pthread_mutex_lock(&(strong->_lock));
  98. ret = true;
  99. pthread_cond_signal(&(strong->_cond));
  100. pthread_mutex_unlock(&(strong->_lock));
  101. }
  102. }
  103. }
  104. }];
  105. pthread_cond_wait(&_cond, &_lock);
  106. pthread_mutex_unlock(&_lock);
  107. }
  108. NSData *data = [[NSFileManager defaultManager] contentsAtPath:localListPath];
  109. _configs = data ? [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil] : nil;
  110. if(_configs == nil){
  111. [_delegate onBGMListLoad:nil];
  112. }
  113. else{
  114. NSArray* nameList = [_configs valueForKeyPath:@"bgm.list.name"];
  115. if([nameList count]){
  116. NSArray* urlList = [_configs valueForKeyPath:@"bgm.list.url"];
  117. for (int i = 0; i < [nameList count]; i++) {
  118. TCBGMElement* ele = [_bgmDict objectForKey:[urlList objectAtIndex:i]];
  119. if(ele != nil){
  120. }
  121. else{
  122. ele = [TCBGMElement new];
  123. ele.netUrl = [urlList objectAtIndex:i];
  124. ele.name = [nameList objectAtIndex:i];
  125. [self saveBGMStat:ele];
  126. }
  127. }
  128. }
  129. }
  130. [_delegate onBGMListLoad:_bgmDict];
  131. }
  132. -(void) initBGMListWithJsonFile:(NSString* _Nonnull)url{
  133. if(url == nil)return;
  134. __weak UGCKitBGMHelper* weak = self;
  135. void (^task)(void) = ^{
  136. [weak _bgmTask:url];
  137. };
  138. dispatch_async(_queue, task);
  139. return;
  140. }
  141. -(void) loadLocalData{
  142. _bgmDict = [NSMutableDictionary new];
  143. _bgmList = [[_userDefaults objectForKey:[_userIDKey stringByAppendingString:@".tc.bgm.list"]] mutableCopy];
  144. if(_bgmList == nil){
  145. _bgmList = [NSMutableDictionary new];
  146. }
  147. for (id it in _bgmList) {
  148. TCBGMElement* ele = [NSKeyedUnarchiver unarchiveObjectWithData:[_userDefaults objectForKey:[_userIDKey stringByAppendingString:it]]];
  149. if(ele) {
  150. [_bgmDict setObject:ele forKey:[ele netUrl]];
  151. }
  152. }
  153. }
  154. -(void) saveBGMStat:(TCBGMElement*) ele{
  155. [_bgmDict setObject:ele forKey:ele.netUrl];
  156. [_bgmList setObject:[ele netUrl] forKey:[ele netUrl]];
  157. NSData *udObject = [NSKeyedArchiver archivedDataWithRootObject:ele];
  158. [_userDefaults setObject:udObject forKey:[_userIDKey stringByAppendingString:[ele netUrl]]];
  159. [_userDefaults setObject:_bgmList forKey:[_userIDKey stringByAppendingString:@".tc.bgm.list"]];
  160. }
  161. - (void)_downloadBGMAction:(TCBGMElement*)current {
  162. const BOOL needOverride = YES;
  163. __strong UGCKitBGMHelper* strong = self;
  164. if(strong != nil){
  165. if([[_currentEle netUrl] isEqualToString:[current netUrl]]){
  166. if([_currentTask state] == NSURLSessionTaskStateRunning){
  167. BGMLog(ASLocalizedString(@"暂停:%@"), [current name]);
  168. [_currentTask suspend];
  169. return;
  170. }
  171. else if([_currentTask state] == NSURLSessionTaskStateSuspended){
  172. BGMLog(ASLocalizedString(@"恢复:%@"), [current name]);
  173. [_currentTask resume];
  174. return;
  175. }
  176. }
  177. else{
  178. if(_currentTask){
  179. if([_currentTask state] != NSURLSessionTaskStateCompleted){
  180. [_currentTask cancel];
  181. [strong.delegate onBGMDownloading:_currentEle percent:0];
  182. }
  183. _currentTask = nil;
  184. }
  185. }
  186. NSString* localListPath = nil;
  187. NSString* url = [current netUrl];
  188. __block NSString* justName = [current name];
  189. if (needOverride) {
  190. localListPath = [_bgmPath stringByAppendingPathComponent:justName];
  191. } else {
  192. justName = [NSString stringWithFormat:@"%@1.%@", [justName stringByDeletingPathExtension], [[current name] pathExtension]];
  193. localListPath = [_bgmPath stringByAppendingPathComponent:justName];
  194. }
  195. __weak __typeof(self) weak = self;
  196. NSURLSessionDownloadTask* task = [self downloadFile:url dstUrl:localListPath callback:^(float percent, NSString* path){
  197. __strong UGCKitBGMHelper* strong = weak;
  198. if(strong){
  199. dispatch_queue_t queue = strong->_queue;
  200. if(percent < 0){
  201. dispatch_async(queue, ^{
  202. [strong.delegate onBGMDownloadDone:current];
  203. });
  204. }
  205. else{
  206. TCBGMElement* ele = [strong->_bgmDict objectForKey:[current netUrl]];
  207. if(path != nil){
  208. ele.localUrl = [NSString stringWithFormat:@"Documents/bgm/%@", justName];
  209. ele.isValid = [NSNumber numberWithBool:true];
  210. dispatch_async(queue, ^{
  211. [strong.delegate onBGMDownloadDone:ele];
  212. });
  213. [strong saveBGMStat:ele];
  214. }else{
  215. dispatch_async(queue, ^{
  216. [weak.delegate onBGMDownloading:ele percent:percent];
  217. });
  218. }
  219. }
  220. }
  221. }];
  222. _currentTask = task;
  223. _currentEle = current;
  224. }
  225. }
  226. #pragma mark NSURLSessionDownloadDelegate
  227. - (void)URLSession:(NSURLSession *)session
  228. task:(NSURLSessionTask *)urlTask
  229. didCompleteWithError:(NSError *)error {
  230. TCBGMDownloadTask *task = nil;
  231. @synchronized (_taskDictionary) {
  232. task = _taskDictionary[urlTask];
  233. }
  234. if (error) {
  235. if (task.callback) {
  236. task.callback(-1, nil);
  237. }
  238. }
  239. @synchronized (_taskDictionary) {
  240. [_taskDictionary removeObjectForKey:urlTask];
  241. }
  242. }
  243. - (void)URLSession:(NSURLSession *)session
  244. downloadTask:(nonnull NSURLSessionDownloadTask *)downloadTask
  245. didWriteData:(int64_t)bytesWritten
  246. totalBytesWritten:(int64_t)totalBytesWritten
  247. totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
  248. TCBGMDownloadTask *task = nil;
  249. @synchronized (_taskDictionary) {
  250. task = _taskDictionary[downloadTask];
  251. }
  252. if (task.callback) {
  253. task.callback(totalBytesWritten / (float)totalBytesExpectedToWrite, nil);
  254. }
  255. }
  256. - (void)URLSession:(NSURLSession *)session
  257. downloadTask:(NSURLSessionDownloadTask *)downloadTask
  258. didFinishDownloadingToURL:(NSURL *)location {
  259. TCBGMDownloadTask *task = nil;
  260. @synchronized (_taskDictionary) {
  261. task = _taskDictionary[downloadTask];
  262. }
  263. NSError *fsError = nil;
  264. NSFileManager *manager = [NSFileManager defaultManager];
  265. if ([manager fileExistsAtPath:task.destPath]) {
  266. [manager removeItemAtPath:task.destPath error:nil];
  267. }
  268. [[NSFileManager defaultManager] moveItemAtURL:location
  269. toURL:[NSURL fileURLWithPath: task.destPath]
  270. error:&fsError];
  271. if (task.callback) {
  272. if (fsError) {
  273. NSLog(@"Error: %@", fsError);
  274. task.callback(-1, nil);
  275. } else {
  276. task.callback(0, task.destPath);
  277. }
  278. }
  279. }
  280. -(void) downloadBGM:(TCBGMElement*) current{
  281. __weak UGCKitBGMHelper* weak = self;
  282. dispatch_async(_queue, ^(){
  283. [weak _downloadBGMAction:current];
  284. });
  285. }
  286. //-(void) pauseAllTasks{
  287. // __weak TCBGMHelper* weak = self;
  288. // dispatch_async(_queue, ^(){
  289. // __strong TCBGMHelper* strong = weak;
  290. // for (id item in strong->_tasks) {
  291. // if([item state] == NSURLSessionTaskStateRunning)[item suspend];
  292. // }
  293. // });
  294. //}
  295. //
  296. //-(void) resumeAllTasks{
  297. // __weak TCBGMHelper* weak = self;
  298. // dispatch_async(_queue, ^(){
  299. // __strong TCBGMHelper* strong = weak;
  300. // for (id item in strong->_tasks) {
  301. // if([item state] == NSURLSessionTaskStateSuspended)[item resume];
  302. // }
  303. // });
  304. //}
  305. /**
  306. 下载函数回调
  307. @param callback 下载进度 < 0 出错并终止
  308. @param srcUrl 最终文件地址 nil != url则下载完成
  309. */
  310. - (NSURLSessionDownloadTask*) downloadFile:(NSString*)srcUrl dstUrl:(NSString*)dstUrl callback:(DownLoadCallback)callback{
  311. TCBGMDownloadTask *task = [[TCBGMDownloadTask alloc] init];
  312. task.destPath = dstUrl;
  313. task.callback = callback;
  314. NSURL *url = [NSURL URLWithString:srcUrl];
  315. NSURLRequest *downloadReq = [NSURLRequest requestWithURL:url
  316. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  317. timeoutInterval:300.f];
  318. NSURLSessionDownloadTask *urlSessionTask = [_urlSession downloadTaskWithRequest:downloadReq];
  319. @synchronized (_taskDictionary) {
  320. _taskDictionary[urlSessionTask] = task;
  321. }
  322. [urlSessionTask resume];
  323. return urlSessionTask;
  324. }
  325. @end
  326. @implementation TCBGMElement
  327. - (id) initWithCoder: (NSCoder *)coder
  328. {
  329. if (self = [super init])
  330. {
  331. self.name = [coder decodeObjectForKey:@"name"];
  332. self.netUrl = [coder decodeObjectForKey:@"netUrl"];
  333. self.localUrl = [coder decodeObjectForKey:@"localUrl"];
  334. self.author = [coder decodeObjectForKey:@"author"];
  335. self.title = [coder decodeObjectForKey:@"title"];
  336. self.isValid = [coder decodeObjectForKey:@"isValid"];
  337. self.duration = [coder decodeObjectForKey:@"duration"];
  338. }
  339. return self;
  340. }
  341. - (void) encodeWithCoder: (NSCoder *)coder
  342. {
  343. [coder encodeObject:_name forKey:@"name"];
  344. [coder encodeObject:_netUrl forKey:@"netUrl"];
  345. [coder encodeObject:_localUrl forKey:@"localUrl"];
  346. [coder encodeObject:_author forKey:@"author"];
  347. [coder encodeObject:_title forKey:@"title"];
  348. [coder encodeObject:_isValid forKey:@"isValid"];
  349. [coder encodeObject:_duration forKey:@"duration"];
  350. }
  351. @end