CCMain.m 220 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189
  1. //
  2. // CCMain.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotos.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import "OCActivity.h"
  29. #import "OCNotifications.h"
  30. #import "OCNotificationsAction.h"
  31. #import "OCFrameworkConstants.h"
  32. #import "OCCapabilities.h"
  33. #import "CTAssetCheckmark.h"
  34. #import "JDStatusBarNotification.h"
  35. #import "NCAutoUpload.h"
  36. #import "NCBridgeSwift.h"
  37. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate, UITextViewDelegate, createFormUploadAssetsDelegate, MGSwipeTableCellDelegate, CCLoginDelegate, CCLoginDelegateWeb>
  38. {
  39. tableMetadata *_metadata;
  40. BOOL _isRoot;
  41. BOOL _isViewDidLoad;
  42. BOOL _isSelectedMode;
  43. NSMutableDictionary *_selectedFileIDsMetadatas;
  44. NSUInteger _numSelectedFileIDsMetadatas;
  45. NSMutableArray *_queueSelector;
  46. NSMutableDictionary *_statusSwipeCell;
  47. UIImageView *_ImageTitleHomeCryptoCloud;
  48. UIView *_reMenuBackgroundView;
  49. UITapGestureRecognizer *_singleFingerTap;
  50. NSString *_directoryGroupBy;
  51. NSString *_directoryOrder;
  52. NSUInteger _failedAttempts;
  53. NSDate *_lockUntilDate;
  54. NSString *_fatherPermission;
  55. UIRefreshControl *_refreshControl;
  56. UIDocumentInteractionController *_docController;
  57. CCHud *_hud;
  58. CCHud *_hudDeterminate;
  59. // Datasource
  60. CCSectionDataSourceMetadata *_sectionDataSource;
  61. NSDate *_dateReadDataSource;
  62. // Search
  63. BOOL _isSearchMode;
  64. NSString *_searchFileName;
  65. NSMutableArray *_searchResultMetadatas;
  66. NSString *_noFilesSearchTitle;
  67. NSString *_noFilesSearchDescription;
  68. NSTimer *_timerWaitInput;
  69. // Login
  70. CCLoginWeb *_loginWeb;
  71. CCLogin *_loginVC;
  72. BOOL _loadingFolder;
  73. }
  74. @end
  75. @implementation CCMain
  76. #pragma --------------------------------------------------------------------------------------------
  77. #pragma mark ===== Init =====
  78. #pragma --------------------------------------------------------------------------------------------
  79. - (id)initWithCoder:(NSCoder *)aDecoder
  80. {
  81. if (self = [super initWithCoder:aDecoder]) {
  82. _directoryOrder = [CCUtility getOrderSettings];
  83. _directoryGroupBy = [CCUtility getGroupBySettings];
  84. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  85. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  86. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  89. }
  90. return self;
  91. }
  92. #pragma --------------------------------------------------------------------------------------------
  93. #pragma mark ===== View =====
  94. #pragma --------------------------------------------------------------------------------------------
  95. - (void)viewDidLoad
  96. {
  97. [super viewDidLoad];
  98. // init object
  99. _metadata = [tableMetadata new];
  100. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  101. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  102. _selectedFileIDsMetadatas = [NSMutableDictionary new];
  103. _statusSwipeCell = [NSMutableDictionary new];
  104. _queueSelector = [NSMutableArray new];
  105. _isViewDidLoad = YES;
  106. _fatherPermission = @"";
  107. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  108. _searchResultMetadatas = [NSMutableArray new];
  109. _searchFileName = @"";
  110. _noFilesSearchTitle = @"";
  111. _noFilesSearchDescription = @"";
  112. // delegate
  113. self.tableView.delegate = self;
  114. self.tableView.tableFooterView = [UIView new];
  115. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  116. self.tableView.emptyDataSetDelegate = self;
  117. self.tableView.emptyDataSetSource = self;
  118. self.searchController.delegate = self;
  119. self.searchController.searchBar.delegate = self;
  120. [CCNetworking sharedNetworking].delegate = self;
  121. // Custom Cell
  122. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  123. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  124. // long press recognizer TableView
  125. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  126. [self.tableView addGestureRecognizer:longPressRecognizer];
  127. // Pull-to-Refresh
  128. [self createRefreshControl];
  129. // Register for 3D Touch Previewing if available
  130. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  131. {
  132. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  133. }
  134. // Back Button
  135. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  136. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"] style:UIBarButtonItemStylePlain target:nil action:nil];
  137. // reMenu Background
  138. _reMenuBackgroundView = [[UIView alloc] init];
  139. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  140. // if this is not Main (the Main uses inizializeMain)
  141. if (_isRoot == NO && app.activeAccount.length > 0) {
  142. // Settings this folder & delegate & Loading datasource
  143. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  144. // Load Datasource
  145. [self reloadDatasource:_serverUrl];
  146. // Read (File) Folder
  147. [self readFileReloadFolder];
  148. }
  149. // Title
  150. [self setTitle];
  151. // Search
  152. self.definesPresentationContext = YES;
  153. self.searchController.searchResultsUpdater = self;
  154. self.searchController.dimsBackgroundDuringPresentation = NO;
  155. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  156. [self.searchController.searchBar sizeToFit];
  157. self.searchController.searchBar.delegate = self;
  158. if (@available(iOS 11, *)) {
  159. self.navigationItem.searchController = self.searchController;
  160. self.navigationItem.hidesSearchBarWhenScrolling = true;
  161. self.navigationItem.searchController.searchBar.tintColor = [UIColor whiteColor];
  162. UITextField *textField = [self.searchController.searchBar valueForKey:@"searchField"];
  163. textField.textColor = [UIColor blackColor];
  164. textField.tintColor = [UIColor blackColor];
  165. UIView *backgroundView = textField.subviews.firstObject;
  166. backgroundView.backgroundColor = UIColor.whiteColor;
  167. backgroundView.layer.cornerRadius = 10;
  168. backgroundView.clipsToBounds = YES;
  169. } else {
  170. self.tableView.tableHeaderView = self.searchController.searchBar;
  171. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  172. }
  173. }
  174. // Apparirà
  175. - (void)viewWillAppear:(BOOL)animated
  176. {
  177. [super viewWillAppear:animated];
  178. // test
  179. if (app.activeAccount.length == 0)
  180. return;
  181. // Settings this folder & delegate & Loading datasource
  182. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  183. [CCNetworking sharedNetworking].delegate = self;
  184. // Color
  185. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  186. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  187. if (_isSelectedMode)
  188. [self setUINavigationBarSelected];
  189. else
  190. [self setUINavigationBarDefault];
  191. // If not editing mode remove _selectedFileIDs
  192. if (!self.tableView.editing)
  193. [_selectedFileIDsMetadatas removeAllObjects];
  194. // Plus Button
  195. [app plusButtonVisibile:true];
  196. }
  197. // E' arrivato
  198. - (void)viewDidAppear:(BOOL)animated
  199. {
  200. [super viewDidAppear:animated];
  201. // Active Main
  202. app.activeMain = self;
  203. // Test viewDidLoad
  204. if (_isViewDidLoad) {
  205. _isViewDidLoad = NO;
  206. } else {
  207. if (app.activeAccount.length > 0 && [_selectedFileIDsMetadatas count] == 0) {
  208. // Load Datasource
  209. [self reloadDatasource:_serverUrl];
  210. // Read (file) Folder
  211. [self readFileReloadFolder];
  212. }
  213. }
  214. // Title
  215. [self setTitle];
  216. }
  217. - (void)viewWillDisappear:(BOOL)animated
  218. {
  219. [super viewWillDisappear:animated];
  220. [self closeAllMenu];
  221. }
  222. - (void)didReceiveMemoryWarning
  223. {
  224. [super didReceiveMemoryWarning];
  225. // Dispose of any resources that can be recreated.
  226. }
  227. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  228. {
  229. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  230. [self closeAllMenu];
  231. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  232. if (self.view.frame.size.width == ([[UIScreen mainScreen] bounds].size.width*([[UIScreen mainScreen] bounds].size.width<[[UIScreen mainScreen] bounds].size.height))+([[UIScreen mainScreen] bounds].size.height*([[UIScreen mainScreen] bounds].size.width>[[UIScreen mainScreen] bounds].size.height))) {
  233. // Portrait
  234. } else {
  235. // Landscape
  236. }
  237. [self.tableView reloadData];
  238. }];
  239. }
  240. - (BOOL)prefersStatusBarHidden
  241. {
  242. return NO;
  243. }
  244. // detect scroll for remove keyboard in search mode
  245. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  246. {
  247. if (_isSearchMode && scrollView == self.tableView) {
  248. [self.searchController.searchBar endEditing:YES];
  249. }
  250. }
  251. - (void)changeTheming
  252. {
  253. if (self.isViewLoaded && self.view.window)
  254. [app changeTheming:self];
  255. // Refresh control
  256. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  257. // Reload Table View
  258. [self tableViewReloadData];
  259. }
  260. #pragma --------------------------------------------------------------------------------------------
  261. #pragma mark ===== Initizlize Mail =====
  262. #pragma --------------------------------------------------------------------------------------------
  263. - (void)initializeMain:(NSNotification *)notification
  264. {
  265. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  266. _directoryGroupBy = nil;
  267. _directoryOrder = nil;
  268. _dateReadDataSource = nil;
  269. // test
  270. if (app.activeAccount.length == 0)
  271. return;
  272. if ([app.listMainVC count] == 0 || _isRoot) {
  273. // This is Root home main add list
  274. appDelegate.homeMain = self;
  275. _isRoot = YES;
  276. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  277. appDelegate.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  278. [appDelegate.listMainVC setObject:self forKey:_serverUrl];
  279. // go Home
  280. [self.navigationController popToRootViewControllerAnimated:NO];
  281. // setting Networking
  282. [CCNetworking sharedNetworking].delegate = self;
  283. [[CCNetworking sharedNetworking] settingAccount];
  284. // Remove search mode
  285. [self cancelSearchBar];
  286. // populate shared Link & User
  287. NSArray *results = [[NCManageDatabase sharedInstance] getShares];
  288. if (results) {
  289. appDelegate.sharesLink = results[0];
  290. appDelegate.sharesUserAndGroup = results[1];
  291. }
  292. // Load Datasource
  293. [self reloadDatasource:_serverUrl];
  294. // Read (File) Folder
  295. [self readFileReloadFolder];
  296. // Setting Theming
  297. [app settingThemingColorBrand];
  298. // Load photo datasorce
  299. if (appDelegate.activePhotos)
  300. [appDelegate.activePhotos reloadDatasourceForced];
  301. // remove all of detail
  302. if (appDelegate.activeDetail)
  303. [appDelegate.activeDetail removeAllView];
  304. // remove all Notification Messages
  305. [appDelegate.listOfNotifications removeAllObjects];
  306. // Not Photos Video in library ? then align
  307. NSArray *recordsPhotoLibrary = [[NCManageDatabase sharedInstance] getPhotoLibraryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", app.activeAccount]];
  308. if ([recordsPhotoLibrary count] == 0) {
  309. [[NCAutoUpload sharedInstance] alignPhotoLibrary];
  310. }
  311. // Initializations
  312. [appDelegate applicationInitialized];
  313. } else {
  314. // reload datasource
  315. [self reloadDatasource:_serverUrl];
  316. }
  317. }
  318. #pragma --------------------------------------------------------------------------------------------
  319. #pragma mark ==== DZNEmptyDataSetSource ====
  320. #pragma --------------------------------------------------------------------------------------------
  321. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  322. {
  323. if (_loadingFolder)
  324. return NO;
  325. else
  326. return YES;
  327. }
  328. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  329. {
  330. return [UIColor whiteColor];
  331. }
  332. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  333. {
  334. if (_isSearchMode)
  335. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"searchBig"] color:[NCBrandColor sharedInstance].brand];
  336. else
  337. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] color:[NCBrandColor sharedInstance].brand];
  338. }
  339. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  340. {
  341. if (_loadingFolder && _refreshControl.isRefreshing == NO) {
  342. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  343. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  344. activityView.color = [NCBrandColor sharedInstance].brand;
  345. [activityView startAnimating];
  346. return activityView;
  347. }
  348. return nil;
  349. }
  350. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  351. {
  352. NSString *text;
  353. if (_isSearchMode) {
  354. text = _noFilesSearchTitle;
  355. } else {
  356. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  357. }
  358. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  359. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  360. }
  361. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  362. {
  363. NSString *text;
  364. if (_isSearchMode) {
  365. text = _noFilesSearchDescription;
  366. } else {
  367. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  368. }
  369. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  370. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  371. paragraph.alignment = NSTextAlignmentCenter;
  372. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  373. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  374. }
  375. #pragma --------------------------------------------------------------------------------------------
  376. #pragma mark ===== Text Field =====
  377. #pragma --------------------------------------------------------------------------------------------
  378. - (void)minCharTextFieldDidChange:(UITextField *)sender
  379. {
  380. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  381. if (alertController)
  382. {
  383. UITextField *fileName = alertController.textFields.firstObject;
  384. UIAlertAction *okAction = alertController.actions.lastObject;
  385. okAction.enabled = fileName.text.length > 0;
  386. }
  387. }
  388. - (void)textFieldDidBeginEditing:(UITextField *)textField{
  389. [textField selectAll:textField];
  390. }
  391. #pragma --------------------------------------------------------------------------------------------
  392. #pragma mark ===== Graphic Window =====
  393. #pragma --------------------------------------------------------------------------------------------
  394. - (void)createRefreshControl
  395. {
  396. _refreshControl = [UIRefreshControl new];
  397. if (@available(iOS 11.0, *)) {
  398. [self.tableView setRefreshControl:_refreshControl];
  399. _refreshControl.tintColor = [UIColor whiteColor];
  400. } else {
  401. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  402. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  403. [self setRefreshControl:_refreshControl];
  404. }
  405. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  406. }
  407. - (void)deleteRefreshControl
  408. {
  409. [_refreshControl endRefreshing];
  410. self.refreshControl = nil;
  411. }
  412. - (void)refreshControlTarget
  413. {
  414. [self readFolder:_serverUrl];
  415. // Actuate `Peek` feedback (weak boom)
  416. AudioServicesPlaySystemSound(1519);
  417. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  418. }
  419. - (void)setTitle
  420. {
  421. // Color text self.navigationItem.title
  422. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  423. if (_isSelectedMode) {
  424. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  425. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  426. self.navigationItem.titleView = nil;
  427. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  428. } else {
  429. // we are in home : LOGO BRAND
  430. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  431. self.navigationItem.title = nil;
  432. if ([app.reachability isReachable] == NO)
  433. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  434. else
  435. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"]];
  436. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  437. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo:)];
  438. [singleTap setNumberOfTapsRequired:1];
  439. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  440. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  441. } else {
  442. self.navigationItem.title = _titleMain;
  443. }
  444. }
  445. }
  446. - (void)setUINavigationBarDefault
  447. {
  448. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  449. UIBarButtonItem *buttonMore, *buttonNotification;
  450. // =
  451. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  452. buttonMore.enabled = true;
  453. // <
  454. self.navigationController.navigationBar.hidden = NO;
  455. // Notification
  456. if ([app.listOfNotifications count] > 0) {
  457. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  458. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  459. buttonNotification.enabled = true;
  460. }
  461. if (buttonNotification)
  462. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  463. else
  464. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  465. self.navigationItem.leftBarButtonItem = nil;
  466. }
  467. - (void)setUINavigationBarSelected
  468. {
  469. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  470. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  471. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  472. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  473. self.navigationItem.leftBarButtonItem = leftButton;
  474. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  475. }
  476. - (void)cancelSelect
  477. {
  478. [self tableViewSelect:NO];
  479. [app.reSelectMenu close];
  480. }
  481. - (void)closeAllMenu
  482. {
  483. // close Menu
  484. [app.reSelectMenu close];
  485. [app.reMainMenu close];
  486. // Close Menu Logo
  487. [CCMenuAccount dismissMenu];
  488. }
  489. #pragma --------------------------------------------------------------------------------------------
  490. #pragma mark ===== Document Picker =====
  491. #pragma --------------------------------------------------------------------------------------------
  492. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  493. {
  494. NSLog(@"[LOG] Cancelled");
  495. }
  496. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  497. {
  498. NSLog(@"[LOG] Cancelled");
  499. }
  500. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  501. {
  502. documentPicker.delegate = self;
  503. [self presentViewController:documentPicker animated:YES completion:nil];
  504. }
  505. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  506. {
  507. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  508. NSString *serverUrl = [app getTabBarControllerActiveServerUrl];
  509. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  510. __block NSError *error;
  511. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  512. NSString *fileName = [url lastPathComponent];
  513. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  514. NSData *data = [NSData dataWithContentsOfURL:newURL];
  515. if (data && error == nil) {
  516. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  517. // Upload File
  518. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:serverUrl session:k_upload_session taskStatus: k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  519. } else {
  520. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  521. }
  522. } else {
  523. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  524. }
  525. }];
  526. }
  527. }
  528. - (void)openImportDocumentPicker
  529. {
  530. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  531. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  532. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  533. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  534. documentProviderMenu.delegate = self;
  535. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  536. }
  537. #pragma --------------------------------------------------------------------------------------------
  538. #pragma mark ===== Assets Picker =====
  539. #pragma --------------------------------------------------------------------------------------------
  540. -(void)dismissFormUploadAssets
  541. {
  542. [self reloadDatasource];
  543. }
  544. - (void)openAssetsPickerController
  545. {
  546. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  547. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  548. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  549. //UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil]; // DEPRECATED iOS9
  550. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedInInstancesOfClasses:@[[CTAssetsPickerController class]]];
  551. [app aspectNavigationControllerBar:navBar online:YES hidden:NO];
  552. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  553. dispatch_async(dispatch_get_main_queue(), ^{
  554. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  555. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeBottom];
  556. // init picker
  557. CTAssetsPickerController *picker = [CTAssetsPickerController new];
  558. // set delegate
  559. picker.delegate = self;
  560. // to show selection order
  561. //picker.showsSelectionIndex = YES;
  562. // to present picker as a form sheet in iPad
  563. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  564. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  565. // present picker
  566. [self presentViewController:picker animated:YES completion:nil];
  567. });
  568. }];
  569. }
  570. - (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
  571. {
  572. if (picker.selectedAssets.count > k_pickerControllerMax) {
  573. [app messageNotification:@"_info_" description:@"_limited_dimension_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  574. return NO;
  575. }
  576. return YES;
  577. }
  578. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  579. {
  580. [picker dismissViewControllerAnimated:YES completion:^{
  581. NSString *serverUrl = [app getTabBarControllerActiveServerUrl];
  582. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] initWithServerUrl:serverUrl assets:assets cryptated:NO session:k_upload_session delegate:self];
  583. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  584. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  585. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  586. [self presentViewController:navigationController animated:YES completion:nil];
  587. }];
  588. }
  589. // New folder or new photo or video
  590. - (void)returnCreate:(NSInteger)type
  591. {
  592. switch (type) {
  593. case k_returnCreateFolderPlain: {
  594. NSString *serverUrl = [app getTabBarControllerActiveServerUrl];
  595. NSString *message;
  596. UIAlertController *alertController;
  597. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  598. message = @"/";
  599. } else {
  600. message = [serverUrl lastPathComponent];
  601. }
  602. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  603. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  604. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  605. textField.autocapitalizationType = UITextAutocapitalizationTypeWords;
  606. }];
  607. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  608. NSLog(@"[LOG] Cancel action");
  609. }];
  610. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  611. UITextField *fileName = alertController.textFields.firstObject;
  612. [self createFolder:fileName.text serverUrl:serverUrl];
  613. }];
  614. okAction.enabled = NO;
  615. [alertController addAction:cancelAction];
  616. [alertController addAction:okAction];
  617. [self presentViewController:alertController animated:YES completion:nil];
  618. }
  619. break;
  620. case k_returnCreateFotoVideoPlain: {
  621. [self openAssetsPickerController];
  622. }
  623. break;
  624. case k_returnCreateFilePlain: {
  625. [self openImportDocumentPicker];
  626. }
  627. break;
  628. case k_returnCreateFotoVideoEncrypted: {
  629. [self openAssetsPickerController];
  630. }
  631. break;
  632. case k_returnCreateFileEncrypted: {
  633. [self openImportDocumentPicker];
  634. }
  635. break;
  636. case k_returnCreateFileText: {
  637. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"NCText" bundle:nil] instantiateViewControllerWithIdentifier:@"NCText"];
  638. navigationController.modalPresentationStyle = UIModalPresentationPageSheet;
  639. [self presentViewController:navigationController animated:YES completion:nil];
  640. }
  641. break;
  642. }
  643. }
  644. #pragma --------------------------------------------------------------------------------------------
  645. #pragma mark ===== Save selected File =====
  646. #pragma --------------------------------------------------------------------------------------------
  647. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  648. {
  649. if (error)
  650. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  651. else
  652. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  653. }
  654. - (void)saveSelectedFiles
  655. {
  656. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  657. return;
  658. NSLog(@"[LOG] Start download selected files ...");
  659. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  660. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  661. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  662. for (tableMetadata *metadata in metadatas) {
  663. if (metadata.directory == NO && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  664. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  665. if (serverUrl)
  666. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  667. }
  668. }
  669. [_hud hideHud];
  670. });
  671. [self tableViewSelect:NO];
  672. }
  673. #pragma --------------------------------------------------------------------------------------------
  674. #pragma mark === Delegate Login ===
  675. #pragma --------------------------------------------------------------------------------------------
  676. - (void)loginSuccess:(NSInteger)loginType
  677. {
  678. [self readFolder:_serverUrl];
  679. }
  680. - (void)loginDisappear
  681. {
  682. app.activeLogin = nil;
  683. }
  684. #pragma mark -
  685. #pragma --------------------------------------------------------------------------------------------
  686. #pragma mark ===== Peek & Pop =====
  687. #pragma --------------------------------------------------------------------------------------------
  688. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  689. {
  690. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  691. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  692. if (metadata.thumbnailExists) {
  693. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  694. if (cell) {
  695. previewingContext.sourceRect = cell.frame;
  696. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  697. vc.delegate = self;
  698. vc.metadata = metadata;
  699. return vc;
  700. }
  701. }
  702. return nil;
  703. }
  704. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  705. {
  706. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  707. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  708. }
  709. #pragma mark -
  710. #pragma --------------------------------------------------------------------------------------------
  711. #pragma mark ==== External Sites ====
  712. #pragma --------------------------------------------------------------------------------------------
  713. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  714. {
  715. [[NCManageDatabase sharedInstance] deleteExternalSites];
  716. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  717. [[NCManageDatabase sharedInstance] addExternalSites:tableExternalSites];
  718. }
  719. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  720. {
  721. NSString *error = [NSString stringWithFormat:@"Get external site failure error %lu, %@", (long)errorCode, message];
  722. NSLog(@"[LOG] %@", error);
  723. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get External Sites Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  724. }
  725. #pragma --------------------------------------------------------------------------------------------
  726. #pragma mark ==== Activity ====
  727. #pragma --------------------------------------------------------------------------------------------
  728. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  729. {
  730. [[NCManageDatabase sharedInstance] addActivityServer:listOfActivity];
  731. // Reload Activity Data Source
  732. [app.activeActivity reloadDatasource];
  733. }
  734. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  735. {
  736. NSString *error = [NSString stringWithFormat:@"Get Activity Server failure error %lu, %@", (long)errorCode, message];
  737. NSLog(@"[LOG] %@", error);
  738. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Activity Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  739. }
  740. #pragma --------------------------------------------------------------------------------------------
  741. #pragma mark ==== Notification ====
  742. #pragma --------------------------------------------------------------------------------------------
  743. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  744. {
  745. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  746. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  747. // Order by date
  748. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  749. OCNotifications *notification1 = obj1, *notification2 = obj2;
  750. return [notification2.date compare: notification1.date];
  751. }];
  752. // verify if listOfNotifications is changed
  753. NSString *old = @"", *new = @"";
  754. for (OCNotifications *notification in listOfNotifications)
  755. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  756. for (OCNotifications *notification in appDelegate.listOfNotifications)
  757. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  758. if (![new isEqualToString:old]) {
  759. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  760. // reload Notification view
  761. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"notificationReloadData" object:nil];
  762. }
  763. // Update NavigationBar
  764. if (!_isSelectedMode) {
  765. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  766. }
  767. });
  768. }
  769. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  770. {
  771. NSString *error = [NSString stringWithFormat:@"Get Notification Server failure error %lu, %@", (long)errorCode, message];
  772. NSLog(@"[LOG] %@", error);
  773. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Notification Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  774. // Update NavigationBar
  775. if (!_isSelectedMode)
  776. [self setUINavigationBarDefault];
  777. }
  778. - (void)viewNotification
  779. {
  780. if ([app.listOfNotifications count] > 0) {
  781. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  782. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  783. [self presentViewController:notificationVC animated:YES completion:nil];
  784. }
  785. }
  786. #pragma --------------------------------------------------------------------------------------------
  787. #pragma mark ==== User Profile ====
  788. #pragma --------------------------------------------------------------------------------------------
  789. - (void)getUserProfileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  790. {
  791. NSString *error = [NSString stringWithFormat:@"Get user profile failure error %lu, %@", (long)errorCode, message];
  792. NSLog(@"[LOG] %@", error);
  793. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get user profile Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  794. }
  795. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  796. {
  797. // Update User (+ userProfile.id)
  798. [[NCManageDatabase sharedInstance] setAccountsUserProfile:userProfile];
  799. // Get Account Active
  800. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  801. // Setting App active account
  802. [app settingActiveAccount:account.account activeUrl:account.url activeUser:account.user activeUserID:account.userID activePassword:account.password];
  803. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  804. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  805. //UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]]; DEPRECATED iOS9
  806. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]]]];
  807. if (avatar)
  808. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  809. else
  810. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  811. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeUserProfile" object:nil];
  812. });
  813. }
  814. #pragma --------------------------------------------------------------------------------------------
  815. #pragma mark ==== Capabilities ====
  816. #pragma --------------------------------------------------------------------------------------------
  817. - (void)getCapabilitiesOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  818. {
  819. // Unauthorized
  820. if (errorCode == kOCErrorServerUnauthorized)
  821. [app openLoginView:self loginType:loginModifyPasswordUser];
  822. NSString *error = [NSString stringWithFormat:@"Get Capabilities failure error %lu, %@", (long)errorCode, message];
  823. NSLog(@"[LOG] %@", error);
  824. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Capabilities of Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  825. // Change Theming color
  826. [app settingThemingColorBrand];
  827. }
  828. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  829. {
  830. // Update capabilities db
  831. [[NCManageDatabase sharedInstance] addCapabilities:capabilities];
  832. // ------ THEMING -----------------------------------------------------------------------
  833. // Download Theming Background & Change Theming color
  834. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  835. if ([NCBrandOptions sharedInstance].use_themingBackground == YES) {
  836. //UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]]; DEPRECATED iOS9
  837. UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]]]];
  838. if (themingBackground)
  839. [UIImagePNGRepresentation(themingBackground) writeToFile:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] atomically:YES];
  840. else
  841. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] error:nil];
  842. }
  843. dispatch_async(dispatch_get_main_queue(), ^{
  844. [app settingThemingColorBrand];
  845. });
  846. });
  847. // ------ SEARCH ------------------------------------------------------------------------
  848. // Search bar if change version
  849. if ([[NCManageDatabase sharedInstance] getServerVersion] != capabilities.versionMajor) {
  850. [self cancelSearchBar];
  851. }
  852. // ------ GET SERVICE SERVER ------------------------------------------------------------
  853. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  854. // Read External Sites
  855. if (capabilities.isExternalSitesServerEnabled) {
  856. metadataNet.action = actionGetExternalSitesServer;
  857. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  858. }
  859. // Read Share
  860. if (capabilities.isFilesSharingAPIEnabled) {
  861. [app.sharesID removeAllObjects];
  862. metadataNet.action = actionReadShareServer;
  863. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  864. }
  865. // Read Notification
  866. metadataNet.action = actionGetNotificationServer;
  867. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  868. // Read User Profile
  869. metadataNet.action = actionGetUserProfile;
  870. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  871. // Read Activity
  872. metadataNet.action = actionGetActivityServer;
  873. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  874. }
  875. #pragma mark -
  876. #pragma --------------------------------------------------------------------------------------------
  877. #pragma mark ==== Request Server Information ====
  878. #pragma --------------------------------------------------------------------------------------------
  879. - (void)requestServerCapabilities
  880. {
  881. // test
  882. if (app.activeAccount.length == 0)
  883. return;
  884. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  885. metadataNet.action = actionGetCapabilities;
  886. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  887. }
  888. #pragma mark -
  889. #pragma --------------------------------------------------------------------------------------------
  890. #pragma mark ==== Middleware Ping ====
  891. #pragma --------------------------------------------------------------------------------------------
  892. - (void)middlewarePing
  893. {
  894. // test
  895. if (app.activeAccount.length == 0)
  896. return;
  897. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  898. metadataNet.action = actionMiddlewarePing;
  899. metadataNet.serverUrl = [[NCBrandOptions sharedInstance] middlewarePingUrl];
  900. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  901. }
  902. #pragma mark -
  903. #pragma --------------------------------------------------------------------------------------------
  904. #pragma mark ==== Download Thumbnail Delegate ====
  905. #pragma --------------------------------------------------------------------------------------------
  906. - (void)downloadThumbnailFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  907. {
  908. NSLog(@"[LOG] Download Thumbnail Failure error %lu, %@", (long)errorCode, message);
  909. }
  910. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  911. {
  912. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  913. if ([self indexPathIsValid:indexPath]) {
  914. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]])
  915. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  916. }
  917. }
  918. #pragma --------------------------------------------------------------------------------------------
  919. #pragma mark ==== Download ====
  920. #pragma --------------------------------------------------------------------------------------------
  921. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  922. {
  923. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  924. // File do not exists on server, remove in local
  925. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  926. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID] error:nil];
  927. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID] error:nil];
  928. if (metadata.directory && serverUrl) {
  929. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  930. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  931. }
  932. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID] clearDateReadDirectoryID:nil];
  933. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  934. }
  935. if ([selector isEqualToString:selectorLoadViewImage]) {
  936. dispatch_async(dispatch_get_main_queue(), ^{
  937. // Updating Detail
  938. if (app.activeDetail)
  939. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  940. // Updating Photos
  941. if (app.activePhotos)
  942. [app.activePhotos downloadFileFailure:errorCode];
  943. });
  944. } else {
  945. if (errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized)
  946. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  947. }
  948. [self reloadDatasource:serverUrl];
  949. }
  950. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  951. {
  952. __block tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  953. if (metadata == nil)
  954. return;
  955. // Download
  956. if ([selector isEqualToString:selectorDownloadFile]) {
  957. [self reloadDatasource:serverUrl];
  958. }
  959. // Synchronized
  960. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  961. [self reloadDatasource:serverUrl];
  962. }
  963. // add Favorite
  964. if ([selector isEqualToString:selectorAddFavorite]) {
  965. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  966. }
  967. // open View File
  968. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  969. [self reloadDatasource:serverUrl];
  970. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  971. selector = selectorOpenIn;
  972. //[self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  973. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  974. selector = selectorOpenIn;
  975. } else {
  976. _metadata = metadata;
  977. if ([self shouldPerformSegue])
  978. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  979. }
  980. }
  981. // Open with...
  982. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  983. [self reloadDatasource:serverUrl];
  984. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName] error:nil];
  985. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName] error:nil];
  986. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName]];
  987. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  988. _docController.delegate = self;
  989. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  990. }
  991. // Save to Photo Album
  992. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  993. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  994. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  995. UIImage *image = [UIImage imageWithContentsOfFile:file];
  996. if (image)
  997. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  998. else
  999. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1000. }
  1001. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1002. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName] error:nil];
  1003. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileName])) {
  1004. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileName], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1005. } else {
  1006. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1007. }
  1008. }
  1009. [self reloadDatasource:serverUrl];
  1010. }
  1011. // Copy File
  1012. if ([selector isEqualToString:selectorLoadCopy]) {
  1013. [self reloadDatasource:serverUrl];
  1014. [self copyFileToPasteboard:metadata];
  1015. }
  1016. //download file plist
  1017. if ([selector isEqualToString:selectorLoadPlist]) {
  1018. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1019. long countSelectorLoadPlist = 0;
  1020. for (NSOperation *operation in [app.netQueue operations]) {
  1021. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1022. countSelectorLoadPlist++;
  1023. }
  1024. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1025. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:directoryID] && directoryID) {
  1026. dispatch_async(dispatch_get_main_queue(), ^{
  1027. [self reloadDatasource:serverUrl];
  1028. });
  1029. }
  1030. });
  1031. }
  1032. //selectorLoadViewImage
  1033. if ([selector isEqualToString:selectorLoadViewImage]) {
  1034. // Detail
  1035. if (app.activeDetail)
  1036. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1037. // Photos
  1038. if (app.activePhotos)
  1039. [app.activePhotos downloadFileSuccess:metadata];
  1040. [self reloadDatasource:serverUrl];
  1041. }
  1042. // if exists postselector call self with selectorPost
  1043. if ([selectorPost length] > 0)
  1044. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1045. // Auto Download Upload
  1046. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1047. // ONLY BACKGROUND
  1048. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1049. } else {
  1050. // ONLY FOREFROUND
  1051. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1052. }
  1053. }
  1054. - (void)downloadSelectedFilesFolders
  1055. {
  1056. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1057. return;
  1058. NSLog(@"[LOG] Start download selected ...");
  1059. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1060. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1061. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1062. for (tableMetadata *metadata in selectedMetadatas) {
  1063. if (metadata.directory) {
  1064. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1065. if (serverUrl) {
  1066. serverUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  1067. [[CCSynchronize sharedSynchronize] readFolder:serverUrl selector:selectorReadFolderWithDownload];
  1068. }
  1069. } else {
  1070. [[CCSynchronize sharedSynchronize] readFile:metadata selector:selectorReadFileWithDownload];
  1071. }
  1072. }
  1073. [_hud hideHud];
  1074. });
  1075. [self tableViewSelect:NO];
  1076. }
  1077. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1078. {
  1079. }
  1080. #pragma --------------------------------------------------------------------------------------------
  1081. #pragma mark ===== Upload new Photos/Videos =====
  1082. #pragma --------------------------------------------------------------------------------------------
  1083. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1084. {
  1085. // Auto Download Upload
  1086. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll] || [selector isEqualToString:selectorUploadFile]) {
  1087. if ([[NCManageDatabase sharedInstance] getPriorityQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier] > k_priorityAutoUploadStop) {
  1088. // Change priority Auto Upload
  1089. if ([[NCManageDatabase sharedInstance] setPriorityQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier priority:k_priorityAutoUploadError]) {
  1090. // Activity
  1091. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:message type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:app.activeUrl];
  1092. }
  1093. if (errorCode != kCFURLErrorCancelled)
  1094. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1095. } else {
  1096. // Delete record on Table Auto Upload
  1097. [[NCManageDatabase sharedInstance] deleteQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier selector:selector];
  1098. // Activity
  1099. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:@"Too many error, file deleted" type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:app.activeUrl];
  1100. [app messageNotification:@"_upload_file_" description:@"Too many error, file deleted, see Activity for more info" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1101. }
  1102. } else {
  1103. // Read File test do not exists
  1104. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1105. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1106. // reUpload
  1107. if (metadata)
  1108. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1109. }
  1110. // Print error
  1111. else if (errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized) {
  1112. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1113. }
  1114. }
  1115. [self reloadDatasource:serverUrl];
  1116. }
  1117. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1118. {
  1119. // Auto Download Upload
  1120. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1121. // ONLY BACKGROUND
  1122. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1123. } else {
  1124. // ONLY FOREFROUND
  1125. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1126. }
  1127. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1128. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1129. [self readFolder:serverUrl];
  1130. } else {
  1131. [self reloadDatasource:serverUrl];
  1132. }
  1133. });
  1134. }
  1135. //
  1136. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1137. //
  1138. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1139. {
  1140. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1141. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1142. });
  1143. }
  1144. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1145. {
  1146. NSArray *assets = [arguments objectAtIndex:0];
  1147. NSString *serverUrl = [arguments objectAtIndex:1];
  1148. BOOL useSubFolder = [[arguments objectAtIndex:2] boolValue];
  1149. NSString *session = [arguments objectAtIndex:3];
  1150. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  1151. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1152. if (!directoryID) return;
  1153. // if request create the folder for Photos & the subfolders
  1154. if ([autoUploadPath isEqualToString:serverUrl])
  1155. if (![[NCAutoUpload sharedInstance] createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  1156. return;
  1157. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1158. for (PHAsset *asset in assets) {
  1159. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType];
  1160. NSDate *assetDate = asset.creationDate;
  1161. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1162. // Create serverUrl if use sub folder
  1163. if (useSubFolder) {
  1164. [formatter setDateFormat:@"yyyy"];
  1165. NSString *yearString = [formatter stringFromDate:assetDate];
  1166. [formatter setDateFormat:@"MM"];
  1167. NSString *monthString = [formatter stringFromDate:assetDate];
  1168. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  1169. }
  1170. // Check if is in upload
  1171. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@ AND session != ''", app.activeAccount, directoryID, fileName];
  1172. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1173. if ([isRecordInSessions count] > 0) {
  1174. // next upload
  1175. continue;
  1176. } else {
  1177. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1178. metadataNet.action = actionReadFile;
  1179. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1180. metadataNet.fileName = fileName;
  1181. metadataNet.session = session;
  1182. metadataNet.selector = selectorReadFileUploadFile;
  1183. metadataNet.serverUrl = serverUrl;
  1184. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1185. }
  1186. }
  1187. }
  1188. #pragma --------------------------------------------------------------------------------------------
  1189. #pragma mark ==== Read File ====
  1190. #pragma --------------------------------------------------------------------------------------------
  1191. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1192. {
  1193. // Unauthorized
  1194. if (errorCode == kOCErrorServerUnauthorized)
  1195. [app openLoginView:self loginType:loginModifyPasswordUser];
  1196. // UploadFile
  1197. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1198. // File not exists
  1199. if (errorCode == 404) {
  1200. metadataNet.errorCode = 0;
  1201. metadataNet.selector = selectorUploadFile;
  1202. metadataNet.selectorPost = nil;
  1203. metadataNet.taskStatus = k_taskStatusResume;
  1204. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1205. } else {
  1206. // error ho many retry befor notification and go to on next asses
  1207. if (metadataNet.errorRetry < 3) {
  1208. // Retry read file
  1209. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1210. } else {
  1211. // STOP check file, view message error
  1212. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1213. }
  1214. }
  1215. }
  1216. }
  1217. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1218. {
  1219. // Read Folder
  1220. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1221. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", metadataNet.account, metadataNet.serverUrl]];
  1222. if ([metadata.etag isEqualToString:directory.etag] == NO) {
  1223. [self readFolder:metadataNet.serverUrl];
  1224. }
  1225. }
  1226. // UploadFile
  1227. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1228. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1229. metadataNet.selector = selectorUploadFile;
  1230. metadataNet.selectorPost = nil;
  1231. metadataNet.taskStatus = k_taskStatusResume;
  1232. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1233. }
  1234. }
  1235. - (void)readFileReloadFolder
  1236. {
  1237. if (!_serverUrl || !app.activeAccount || app.maintenanceMode)
  1238. return;
  1239. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1240. metadataNet.action = actionReadFile;
  1241. metadataNet.priority = NSOperationQueuePriorityHigh;
  1242. metadataNet.selector = selectorReadFileReloadFolder;
  1243. metadataNet.serverUrl = _serverUrl;
  1244. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1245. }
  1246. #pragma --------------------------------------------------------------------------------------------
  1247. #pragma mark ==== Read Folder ====
  1248. #pragma --------------------------------------------------------------------------------------------
  1249. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1250. {
  1251. // stoprefresh
  1252. [_refreshControl endRefreshing];
  1253. // Unauthorized
  1254. if (errorCode == kOCErrorServerUnauthorized)
  1255. [app openLoginView:self loginType:loginModifyPasswordUser];
  1256. _loadingFolder = NO;
  1257. [self tableViewReloadData];
  1258. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1259. // verify active user
  1260. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1261. if (message && [record.account isEqualToString:metadataNet.account])
  1262. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1263. [self reloadDatasource:metadataNet.serverUrl];
  1264. }
  1265. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas
  1266. {
  1267. // stoprefresh
  1268. [_refreshControl endRefreshing];
  1269. // verify active user
  1270. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1271. if (![record.account isEqualToString:metadataNet.account])
  1272. return;
  1273. // save father e update permission
  1274. if(!_isSearchMode && metadataFolder)
  1275. _fatherPermission = metadataFolder.permissions;
  1276. NSArray *recordsInSessions;
  1277. NSMutableArray *metadatasToInsertInDB = [NSMutableArray new];
  1278. if (_isSearchMode) {
  1279. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1280. } else {
  1281. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:metadataFolder.etag];
  1282. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID] clearDateReadDirectoryID:metadataNet.directoryID];
  1283. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1284. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1285. }
  1286. for (tableMetadata *metadata in metadatas) {
  1287. // verify if the record is in download/upload progress
  1288. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1289. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", app.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1290. // is in Download or Upload
  1291. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1292. continue;
  1293. }
  1294. }
  1295. // Insert in Array
  1296. [metadatasToInsertInDB addObject:metadata];
  1297. }
  1298. // insert in Database
  1299. metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl];
  1300. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1301. // read plist
  1302. if (!_isSearchMode)
  1303. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1304. // File is changed ??
  1305. if (!_isSearchMode && metadatasToInsertInDB)
  1306. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1307. });
  1308. // Search Mode
  1309. if (_isSearchMode) {
  1310. // Fix managed -> Unmanaged _searchResultMetadatas
  1311. if (metadatasToInsertInDB)
  1312. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  1313. [self reloadDatasource:metadataNet.serverUrl];
  1314. }
  1315. // this is the same directory
  1316. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1317. // reload
  1318. [self reloadDatasource:metadataNet.serverUrl];
  1319. // Enable change user
  1320. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1321. _loadingFolder = NO;
  1322. [self tableViewReloadData];
  1323. }
  1324. // Is encrypted folder get metadata
  1325. if (metadataFolder.encrypted == true) {
  1326. [app.endToEndInterface getEndToEndMetadata:metadataFolder];
  1327. }
  1328. }
  1329. - (void)readFolder:(NSString *)serverUrl
  1330. {
  1331. // init control
  1332. if (!serverUrl || !app.activeAccount || app.maintenanceMode) {
  1333. [_refreshControl endRefreshing];
  1334. return;
  1335. }
  1336. // Search Mode
  1337. if (_isSearchMode) {
  1338. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1339. _searchFileName = @""; // forced reload searchg
  1340. [self updateSearchResultsForSearchController:self.searchController];
  1341. return;
  1342. }
  1343. _loadingFolder = YES;
  1344. [self tableViewReloadData];
  1345. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  1346. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1347. metadataNet.action = actionReadFolder;
  1348. metadataNet.date = [NSDate date];
  1349. metadataNet.depth = @"1";
  1350. metadataNet.directoryID = directory.directoryID;
  1351. metadataNet.priority = NSOperationQueuePriorityHigh;
  1352. metadataNet.selector = selectorReadFolder;
  1353. metadataNet.serverUrl = serverUrl;
  1354. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1355. }
  1356. #pragma mark -
  1357. #pragma --------------------------------------------------------------------------------------------
  1358. #pragma mark ===== Search =====
  1359. #pragma --------------------------------------------------------------------------------------------
  1360. -(void)searchStartTimer
  1361. {
  1362. NSString *home = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  1363. [[CCActions sharedInstance] search:home fileName:_searchFileName depth:@"infinity" date:nil selector:selectorSearch delegate:self];
  1364. _noFilesSearchTitle = @"";
  1365. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1366. [self.tableView reloadEmptyDataSet];
  1367. }
  1368. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1369. {
  1370. //[self setNeedsStatusBarAppearanceUpdate];
  1371. _isSearchMode = YES;
  1372. [self deleteRefreshControl];
  1373. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1374. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1375. _searchFileName = fileName;
  1376. // First : filter
  1377. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1378. if (!directoryID) return;
  1379. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileName CONTAINS[cd] %@", directoryID, app.activeAccount, fileName];
  1380. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1381. [_searchResultMetadatas removeAllObjects];
  1382. for (tableMetadata *record in records)
  1383. [_searchResultMetadatas addObject:record];
  1384. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1385. metadataNet.account = app.activeAccount;
  1386. metadataNet.directoryID = directoryID;
  1387. metadataNet.selector = selectorSearch;
  1388. metadataNet.serverUrl = _serverUrl;
  1389. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas];
  1390. // Version >= 12
  1391. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1392. [_timerWaitInput invalidate];
  1393. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1394. }
  1395. }
  1396. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1397. [self reloadDatasource];
  1398. }
  1399. }
  1400. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1401. {
  1402. [self cancelSearchBar];
  1403. [self readFolder:_serverUrl];
  1404. }
  1405. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1406. {
  1407. // Unauthorized
  1408. if (errorCode == kOCErrorServerUnauthorized)
  1409. [app openLoginView:self loginType:loginModifyPasswordUser];
  1410. if (message && errorCode != kOCErrorServerUnauthorized)
  1411. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1412. _searchFileName = @"";
  1413. }
  1414. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1415. {
  1416. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1417. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:metadatas];
  1418. }
  1419. - (void)cancelSearchBar
  1420. {
  1421. if (self.searchController.active) {
  1422. [self.searchController setActive:NO];
  1423. [self createRefreshControl];
  1424. _isSearchMode = NO;
  1425. _searchFileName = @"";
  1426. _dateReadDataSource = nil;
  1427. _searchResultMetadatas = [NSMutableArray new];
  1428. [self reloadDatasource];
  1429. }
  1430. //[self setNeedsStatusBarAppearanceUpdate];
  1431. }
  1432. #pragma mark -
  1433. #pragma --------------------------------------------------------------------------------------------
  1434. #pragma mark ===== Delete File or Folder =====
  1435. #pragma --------------------------------------------------------------------------------------------
  1436. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1437. {
  1438. // Unauthorized
  1439. if (errorCode == kOCErrorServerUnauthorized)
  1440. [app openLoginView:self loginType:loginModifyPasswordUser];
  1441. NSLog(@"[LOG] Delete File failure error %lu, %@", (long)errorCode, message);
  1442. [self deleteFileOrFolderSuccess:metadataNet];
  1443. }
  1444. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1445. {
  1446. [_queueSelector removeObject:metadataNet.selector];
  1447. if ([_queueSelector count] == 0) {
  1448. [_hud hideHud];
  1449. // next
  1450. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1451. if ([_selectedFileIDsMetadatas count] > 0) {
  1452. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1453. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1454. } else {
  1455. // End Select Table View
  1456. [self tableViewSelect:NO];
  1457. // Reload
  1458. if (_isSearchMode)
  1459. [self readFolder:metadataNet.serverUrl];
  1460. else
  1461. [self reloadDatasource:metadataNet.serverUrl];
  1462. }
  1463. }
  1464. }
  1465. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1466. {
  1467. [_queueSelector addObject:selectorDelete];
  1468. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1469. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1470. }
  1471. - (void)deleteFile
  1472. {
  1473. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1474. return;
  1475. [_queueSelector removeAllObjects];
  1476. if ([_selectedFileIDsMetadatas count] > 0) {
  1477. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1478. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1479. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1480. } else {
  1481. _numSelectedFileIDsMetadatas = 1;
  1482. [self deleteFileOrFolder:_metadata numFile:1 ofFile:_numSelectedFileIDsMetadatas];
  1483. }
  1484. }
  1485. #pragma --------------------------------------------------------------------------------------------
  1486. #pragma mark ===== Rename / Move =====
  1487. #pragma --------------------------------------------------------------------------------------------
  1488. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1489. {
  1490. [self readFolder:metadataNet.serverUrl];
  1491. }
  1492. - (void)renameFile:(NSArray *)arguments
  1493. {
  1494. tableMetadata* metadata = [arguments objectAtIndex:0];
  1495. NSString *fileName = [arguments objectAtIndex:1];
  1496. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1497. }
  1498. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1499. {
  1500. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1501. [_hud hideHud];
  1502. if (message && errorCode != kOCErrorServerUnauthorized)
  1503. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1504. // End Select Table View
  1505. [self tableViewSelect:NO];
  1506. // reload Datasource
  1507. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1508. [self readFolder:metadataNet.serverUrl];
  1509. else
  1510. [self reloadDatasource];
  1511. }
  1512. }
  1513. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1514. {
  1515. [_queueSelector removeObject:metadataNet.selector];
  1516. if ([_queueSelector count] == 0) {
  1517. [_hud hideHud];
  1518. NSString *fileName = metadataNet.fileName;
  1519. NSString *directoryID = metadataNet.directoryID;
  1520. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1521. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1522. if (!serverUrlTo) return;
  1523. // FILE -> Metadata
  1524. if (metadataNet.directory == NO)
  1525. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1526. // DIRECTORY -> Directory - CCMetadata
  1527. if (metadataNet.directory == YES) {
  1528. // delete all dir / subdir
  1529. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1530. // move metadata
  1531. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1532. // Add new directory
  1533. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1534. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil];
  1535. }
  1536. // next
  1537. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1538. if ([_selectedFileIDsMetadatas count] > 0) {
  1539. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1540. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1541. } else {
  1542. // End Select Table View
  1543. [self tableViewSelect:NO];
  1544. // reload Datasource
  1545. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1546. [self readFolder:metadataNet.serverUrl];
  1547. else
  1548. [self reloadDatasource];
  1549. }
  1550. }
  1551. }
  1552. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1553. {
  1554. tableMetadata *metadata = [arguments objectAtIndex:0];
  1555. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1556. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1557. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1558. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1559. if (!serverUrl) return;
  1560. NSString *directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1561. if (!directoryIDTo) return;
  1562. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withUserID:app.activeUserID withPassword:app.activePassword withUrl:app.activeUrl];
  1563. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1564. if(!error) {
  1565. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1566. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1567. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1568. }];
  1569. [alert addAction:ok];
  1570. [self presentViewController:alert animated:YES completion:nil];
  1571. });
  1572. // End Select Table View
  1573. [self tableViewSelect:NO];
  1574. // reload Datasource
  1575. [self readFileReloadFolder];
  1576. return;
  1577. }
  1578. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1579. metadataNet.action = actionMoveFileOrFolder;
  1580. metadataNet.directory = metadata.directory;
  1581. metadataNet.fileID = metadata.fileID;
  1582. metadataNet.directoryID = metadata.directoryID;
  1583. metadataNet.directoryIDTo = directoryIDTo;
  1584. metadataNet.fileName = metadata.fileName;
  1585. metadataNet.fileNameTo = metadata.fileName;
  1586. metadataNet.etag = metadata.etag;
  1587. metadataNet.selector = selectorMove;
  1588. metadataNet.serverUrl = serverUrl;
  1589. metadataNet.serverUrlTo = serverUrlTo;
  1590. [_queueSelector addObject:metadataNet.selector];
  1591. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1592. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1593. }
  1594. // DELEGATE : Move
  1595. - (void)dismissMove
  1596. {
  1597. [self reloadDatasource];
  1598. }
  1599. // DELEGATE : Move
  1600. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  1601. {
  1602. [_queueSelector removeAllObjects];
  1603. if ([_selectedFileIDsMetadatas count] > 0) {
  1604. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1605. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1606. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1607. } else {
  1608. _numSelectedFileIDsMetadatas = 1;
  1609. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[_metadata, serverUrlTo, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1610. }
  1611. }
  1612. - (void)moveOpenWindow:(NSArray *)indexPaths
  1613. {
  1614. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1615. return;
  1616. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1617. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1618. viewController.delegate = self;
  1619. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1620. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1621. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1622. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1623. viewController.networkingOperationQueue = app.netQueue;
  1624. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1625. [self presentViewController:navigationController animated:YES completion:nil];
  1626. }
  1627. #pragma --------------------------------------------------------------------------------------------
  1628. #pragma mark ===== Create folder =====
  1629. #pragma --------------------------------------------------------------------------------------------
  1630. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1631. {
  1632. // Unauthorized
  1633. if (errorCode == kOCErrorServerUnauthorized)
  1634. [app openLoginView:self loginType:loginModifyPasswordUser];
  1635. if (message && errorCode != kOCErrorServerUnauthorized)
  1636. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1637. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID] clearDateReadDirectoryID:nil];
  1638. [self reloadDatasource];
  1639. // We are in directory fail ?
  1640. CCMain *vc = [app.listMainVC objectForKey:[CCUtility stringAppendServerUrl:_serverUrl addFileName:metadataNet.fileName]];
  1641. if (vc)
  1642. [vc.navigationController popViewControllerAnimated:YES];
  1643. }
  1644. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1645. {
  1646. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1647. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil];
  1648. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID]];
  1649. if (metadata) {
  1650. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID] clearDateReadDirectoryID:nil];
  1651. metadata.fileID = metadataNet.fileID;
  1652. metadata.date = metadataNet.date;
  1653. metadata.permissions = @"RDNVCK";
  1654. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1655. [self reloadDatasource];
  1656. } else {
  1657. [self readFileReloadFolder];
  1658. }
  1659. }
  1660. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1661. {
  1662. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1663. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1664. if (![fileNameFolder length]) return;
  1665. //if (autoUploadDirectory) metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  1666. //else metadataNet.serverUrl = _serverUrl;
  1667. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1668. if (!directoryID) return;
  1669. metadataNet.action = actionCreateFolder;
  1670. metadataNet.directoryID = directoryID;
  1671. metadataNet.fileID = [[NSUUID UUID] UUIDString];
  1672. metadataNet.fileName = fileNameFolder;
  1673. metadataNet.selector = selectorCreateFolder;
  1674. metadataNet.serverUrl = serverUrl;
  1675. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1676. // Create Directory on metadata
  1677. tableMetadata *metadata = [CCUtility createMetadataWithAccount:app.activeAccount date:[NSDate date] directory:YES fileID:metadataNet.fileID directoryID:metadataNet.directoryID fileName:metadataNet.fileName etag:@"" size:0 status:k_metadataStatusNormal];
  1678. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1679. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_serverUrl directoryID:nil];
  1680. [self reloadDatasource];
  1681. }
  1682. #pragma --------------------------------------------------------------------------------------------
  1683. #pragma mark ===== Progress & Task Button =====
  1684. #pragma --------------------------------------------------------------------------------------------
  1685. - (void)triggerProgressTask:(NSNotification *)notification
  1686. {
  1687. NSDictionary *dict = notification.userInfo;
  1688. NSString *fileID = [dict valueForKey:@"fileID"];
  1689. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1690. float progress = [[dict valueForKey:@"progress"] floatValue];
  1691. // Check
  1692. if (!fileID || [fileID isEqualToString: @""])
  1693. return;
  1694. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1695. if (![serverUrl isEqualToString:_serverUrl])
  1696. return;
  1697. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1698. if ([self indexPathIsValid:indexPath]) {
  1699. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1700. cell.progressView.progressTintColor = [UIColor blackColor];
  1701. cell.progressView.hidden = NO;
  1702. [cell.progressView setProgress:progress];
  1703. }
  1704. }
  1705. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1706. {
  1707. UITouch * touch = [[event allTouches] anyObject];
  1708. CGPoint location = [touch locationInView:self.tableView];
  1709. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1710. if ([self indexPathIsValid:indexPath]) {
  1711. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1712. if (metadata)
  1713. [self reloadTaskButton:metadata];
  1714. }
  1715. }
  1716. - (void)reloadTaskButton:(tableMetadata *)metadata
  1717. {
  1718. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1719. __block NSURLSessionTask *findTask;
  1720. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1721. NSString *fileID = metadata.fileID;
  1722. // DOWNLOAD
  1723. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1724. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1725. for (NSURLSessionUploadTask *task in downloadTasks)
  1726. if (task.taskIdentifier == sessionTaskIdentifier) {
  1727. findTask = task;
  1728. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1729. [task cancel];
  1730. }
  1731. if (!findTask) {
  1732. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1733. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1734. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1735. }
  1736. }];
  1737. }
  1738. // UPLOAD
  1739. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1740. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1741. for (NSURLSessionUploadTask *task in uploadTasks)
  1742. if (task.taskIdentifier == sessionTaskIdentifier) {
  1743. findTask = task;
  1744. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1745. [task cancel];
  1746. }
  1747. if (!findTask) {
  1748. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1749. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1750. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1751. }
  1752. }];
  1753. }
  1754. }
  1755. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1756. {
  1757. UITouch * touch = [[event allTouches] anyObject];
  1758. CGPoint location = [touch locationInView:self.tableView];
  1759. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1760. if ([self indexPathIsValid:indexPath]) {
  1761. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1762. if (metadata)
  1763. [self cancelTaskButton:metadata reloadTable:YES];
  1764. }
  1765. }
  1766. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  1767. {
  1768. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1769. __block NSURLSessionTask *findTask;
  1770. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1771. NSString *fileID = metadata.fileID;
  1772. // DOWNLOAD
  1773. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1774. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1775. for (NSURLSessionTask *task in downloadTasks)
  1776. if (task.taskIdentifier == sessionTaskIdentifier) {
  1777. findTask = task;
  1778. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1779. [task cancel];
  1780. }
  1781. if (!findTask) {
  1782. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1783. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1784. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1785. }
  1786. }];
  1787. }
  1788. // UPLOAD
  1789. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1790. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1791. for (NSURLSessionUploadTask *task in uploadTasks)
  1792. if (task.taskIdentifier == sessionTaskIdentifier) {
  1793. findTask = task;
  1794. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1795. [task cancel];
  1796. }
  1797. if (!findTask) {
  1798. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1799. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1800. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1801. }
  1802. }];
  1803. }
  1804. }
  1805. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  1806. {
  1807. UITouch * touch = [[event allTouches] anyObject];
  1808. CGPoint location = [touch locationInView:self.tableView];
  1809. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1810. if ([self indexPathIsValid:indexPath]) {
  1811. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1812. if (metadata)
  1813. [self stopTaskButton:metadata];
  1814. }
  1815. }
  1816. - (void)stopTaskButton:(tableMetadata *)metadata
  1817. {
  1818. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1819. __block NSURLSessionTask *findTask;
  1820. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1821. NSString *fileID = metadata.fileID;
  1822. // UPLOAD
  1823. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1824. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1825. for (NSURLSessionUploadTask *task in uploadTasks)
  1826. if (task.taskIdentifier == sessionTaskIdentifier) {
  1827. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1828. findTask = task;
  1829. [task cancel];
  1830. }
  1831. if (!findTask) {
  1832. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1833. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1834. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1835. }
  1836. }];
  1837. }
  1838. }
  1839. #pragma --------------------------------------------------------------------------------------------
  1840. #pragma mark ===== Shared =====
  1841. #pragma --------------------------------------------------------------------------------------------
  1842. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1843. {
  1844. [_hud hideHud];
  1845. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1846. // change account ?
  1847. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1848. if([record.account isEqualToString:metadataNet.account] == NO)
  1849. return;
  1850. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  1851. if (result) {
  1852. appDelegate.sharesLink = result[0];
  1853. appDelegate.sharesUserAndGroup = result[1];
  1854. }
  1855. // Notify Shares View
  1856. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  1857. if (openWindow) {
  1858. if (_shareOC) {
  1859. [_shareOC reloadData];
  1860. } else {
  1861. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  1862. // Apriamo la view
  1863. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1864. _shareOC.delegate = self;
  1865. _shareOC.metadata = metadata;
  1866. _shareOC.serverUrl = metadataNet.serverUrl;
  1867. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  1868. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  1869. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1870. [self presentViewController:_shareOC animated:YES completion:nil];
  1871. }
  1872. }
  1873. [self tableViewReloadData];
  1874. }
  1875. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1876. {
  1877. [_hud hideHud];
  1878. // Unauthorized
  1879. if (errorCode == kOCErrorServerUnauthorized)
  1880. [app openLoginView:self loginType:loginModifyPasswordUser];
  1881. if (errorCode != kOCErrorServerUnauthorized)
  1882. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1883. if (_shareOC)
  1884. [_shareOC reloadData];
  1885. [self tableViewReloadData];
  1886. }
  1887. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  1888. {
  1889. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1890. metadataNet.action = actionShare;
  1891. metadataNet.fileID = metadata.fileID;
  1892. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  1893. metadataNet.password = password;
  1894. metadataNet.selector = selectorShare;
  1895. metadataNet.serverUrl = serverUrl;
  1896. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1897. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1898. }
  1899. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  1900. {
  1901. [_hud hideHud];
  1902. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1903. // rimuoviamo la condivisione da db
  1904. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  1905. if (result) {
  1906. appDelegate.sharesLink = result[0];
  1907. appDelegate.sharesUserAndGroup = result[1];
  1908. }
  1909. if (_shareOC)
  1910. [_shareOC reloadData];
  1911. [self tableViewReloadData];
  1912. }
  1913. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  1914. {
  1915. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1916. metadataNet.action = actionUnShare;
  1917. metadataNet.fileID = metadata.fileID;
  1918. metadataNet.fileName = metadata.fileName;
  1919. metadataNet.selector = selectorUnshare;
  1920. metadataNet.serverUrl = serverUrl;
  1921. metadataNet.share = share;
  1922. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1923. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1924. }
  1925. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  1926. {
  1927. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1928. metadataNet.action = actionUpdateShare;
  1929. metadataNet.fileID = metadata.fileID;
  1930. metadataNet.expirationTime = expirationTime;
  1931. metadataNet.password = password;
  1932. metadataNet.selector = selectorUpdateShare;
  1933. metadataNet.serverUrl = serverUrl;
  1934. metadataNet.share = share;
  1935. metadataNet.sharePermission = permission;
  1936. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1937. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1938. }
  1939. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  1940. {
  1941. [_hud hideHud];
  1942. if (_shareOC)
  1943. [_shareOC reloadUserAndGroup:items];
  1944. }
  1945. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1946. {
  1947. [_hud hideHud];
  1948. // Unauthorized
  1949. if (errorCode == kOCErrorServerUnauthorized)
  1950. [app openLoginView:self loginType:loginModifyPasswordUser];
  1951. if (errorCode != kOCErrorServerUnauthorized)
  1952. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1953. }
  1954. - (void)getUserAndGroup:(NSString *)find
  1955. {
  1956. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1957. metadataNet.action = actionGetUserAndGroup;
  1958. metadataNet.options = find;
  1959. metadataNet.selector = selectorGetUserAndGroup;
  1960. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1961. [_hud visibleIndeterminateHud];
  1962. }
  1963. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1964. {
  1965. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1966. metadataNet.action = actionShareWith;
  1967. metadataNet.fileID = metadata.fileID;
  1968. metadataNet.directoryID = directoryID;
  1969. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  1970. metadataNet.serverUrl = serverUrl;
  1971. metadataNet.selector = selectorShare;
  1972. metadataNet.share = user;
  1973. metadataNet.shareeType = shareeType;
  1974. metadataNet.sharePermission = permission;
  1975. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1976. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1977. }
  1978. - (void)openWindowShare:(tableMetadata *)metadata
  1979. {
  1980. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1981. if (!serverUrl) return;
  1982. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1983. metadataNet.action = actionReadShareServer;
  1984. metadataNet.fileID = metadata.fileID;
  1985. metadataNet.fileName = metadata.fileName;
  1986. metadataNet.selector = selectorOpenWindowShare;
  1987. metadataNet.serverUrl = serverUrl;
  1988. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1989. [_hud visibleIndeterminateHud];
  1990. }
  1991. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  1992. {
  1993. CGPoint location = [tapGesture locationInView:self.tableView];
  1994. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1995. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1996. if (metadata)
  1997. [self openWindowShare:metadata];
  1998. }
  1999. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2000. {
  2001. CGPoint location = [tapGesture locationInView:self.tableView];
  2002. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2003. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2004. if (metadata) {
  2005. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2006. vc.metadata = metadata;
  2007. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2008. [self presentViewController:vc animated:YES completion:nil];
  2009. }
  2010. }
  2011. #pragma --------------------------------------------------------------------------------------------
  2012. #pragma mark ===== Favorite =====
  2013. #pragma --------------------------------------------------------------------------------------------
  2014. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2015. {
  2016. _dateReadDataSource = nil;
  2017. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2018. if (_isSearchMode)
  2019. [self readFolder:metadataNet.serverUrl];
  2020. else
  2021. [self reloadDatasource:metadataNet.serverUrl];
  2022. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2023. if (metadata.directory && metadata.favorite) {
  2024. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileName];
  2025. [app.activeFavorites addFavoriteFolder:dir];
  2026. }
  2027. }
  2028. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2029. {
  2030. // Unauthorized
  2031. if (errorCode == kOCErrorServerUnauthorized)
  2032. [app openLoginView:self loginType:loginModifyPasswordUser];
  2033. NSLog(@"[LOG] Setting Favorite failure error %lu, %@", (long)errorCode, message);
  2034. }
  2035. - (void)addFavorite:(tableMetadata *)metadata
  2036. {
  2037. if (metadata.directory) {
  2038. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2039. } else {
  2040. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2041. if (serverUrl)
  2042. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2043. }
  2044. }
  2045. - (void)removeFavorite:(tableMetadata *)metadata
  2046. {
  2047. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2048. }
  2049. #pragma --------------------------------------------------------------------------------------------
  2050. #pragma mark ===== Open in... =====
  2051. #pragma --------------------------------------------------------------------------------------------
  2052. - (void)openIn:(tableMetadata *)metadata
  2053. {
  2054. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2055. if (!serverUrl) return;
  2056. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2057. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2058. if ([self indexPathIsValid:indexPath])
  2059. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2060. }
  2061. #pragma --------------------------------------------------------------------------------------------
  2062. #pragma mark ===== Remove Local File =====
  2063. #pragma --------------------------------------------------------------------------------------------
  2064. - (void)removeLocalFile:(tableMetadata *)metadata
  2065. {
  2066. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2067. if (!serverUrl) return;
  2068. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2069. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2070. [self reloadDatasource:serverUrl];
  2071. }
  2072. #pragma --------------------------------------------------------------------------------------------
  2073. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2074. #pragma --------------------------------------------------------------------------------------------
  2075. - (void)orderTable:(NSString *)order
  2076. {
  2077. [CCUtility setOrderSettings:order];
  2078. // Clear data-read of DataSource
  2079. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2080. }
  2081. - (void)ascendingTable:(BOOL)ascending
  2082. {
  2083. [CCUtility setAscendingSettings:ascending];
  2084. // Clear data-read of DataSource
  2085. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2086. }
  2087. - (void)directoryOnTop:(BOOL)directoryOnTop
  2088. {
  2089. [CCUtility setDirectoryOnTop:directoryOnTop];
  2090. // Clear data-read of DataSource
  2091. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2092. }
  2093. - (void)tableGroupBy:(NSString *)groupBy
  2094. {
  2095. [CCUtility setGroupBySettings:groupBy];
  2096. // Clear data-read of DataSource
  2097. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2098. }
  2099. #pragma --------------------------------------------------------------------------------------------
  2100. #pragma mark ==== Menu LOGO ====
  2101. #pragma --------------------------------------------------------------------------------------------
  2102. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  2103. {
  2104. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2105. return;
  2106. // Brand
  2107. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2108. return;
  2109. NSUInteger numInSession = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", app.activeAccount] sorted:nil ascending:NO] count];
  2110. NSUInteger numInQueue = [app.netQueue operationCount];
  2111. if (numInSession+numInQueue > 0) {
  2112. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  2113. return;
  2114. }
  2115. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2116. NSMutableArray *menuArray = [NSMutableArray new];
  2117. for (NSString *account in listAccount) {
  2118. if ([account isEqualToString:app.activeAccount]) continue;
  2119. CCMenuItem *item = [[CCMenuItem alloc] init];
  2120. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2121. item.argument = account;
  2122. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2123. item.target = self;
  2124. item.action = @selector(changeDefaultAccount:);
  2125. [menuArray addObject:item];
  2126. }
  2127. if ([menuArray count] == 0)
  2128. return;
  2129. OptionalConfiguration options;
  2130. Color textColor, backgroundColor;
  2131. textColor.R = 0;
  2132. textColor.G = 0;
  2133. textColor.B = 0;
  2134. backgroundColor.R = 1;
  2135. backgroundColor.G = 1;
  2136. backgroundColor.B = 1;
  2137. options.arrowSize = 9;
  2138. options.marginXSpacing = 7;
  2139. options.marginYSpacing = 10;
  2140. options.intervalSpacing = 20;
  2141. options.menuCornerRadius = 6.5;
  2142. options.maskToBackground = NO;
  2143. options.shadowOfMenu = YES;
  2144. options.hasSeperatorLine = YES;
  2145. options.seperatorLineHasInsets = YES;
  2146. options.textColor = textColor;
  2147. options.menuBackgroundColor = backgroundColor;
  2148. CGRect rect = self.view.frame;
  2149. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  2150. CGFloat safeAreaTop = 0;
  2151. CGFloat offsetY = 35;
  2152. if (@available(iOS 11, *)) {
  2153. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  2154. }
  2155. rect.origin.y = locationY + safeAreaTop + offsetY;
  2156. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  2157. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2158. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2159. }
  2160. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2161. {
  2162. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2163. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2164. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2165. if (tableAccount) {
  2166. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:tableAccount.password];
  2167. // go to home sweet home
  2168. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2169. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2170. }
  2171. });
  2172. }
  2173. #pragma --------------------------------------------------------------------------------------------
  2174. #pragma mark ==== ReMenu ====
  2175. #pragma --------------------------------------------------------------------------------------------
  2176. - (void)createReMenuBackgroundView:(REMenu *)menu
  2177. {
  2178. CGFloat safeAreaBottom = 0;
  2179. CGFloat safeAreaTop = 0;
  2180. CGFloat statusBar = 0;
  2181. if (@available(iOS 11, *)) {
  2182. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  2183. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  2184. }
  2185. if ([UIApplication sharedApplication].isStatusBarHidden) {
  2186. statusBar = 13;
  2187. }
  2188. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  2189. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  2190. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  2191. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  2192. [UIView animateWithDuration:0.2 animations:^{
  2193. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  2194. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  2195. if (y>minimum) {
  2196. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  2197. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2198. }
  2199. }];
  2200. }
  2201. - (void)createReMainMenu
  2202. {
  2203. NSString *ordinamento;
  2204. NSString *groupBy = _directoryGroupBy;
  2205. __block NSString *nuovoOrdinamento;
  2206. NSString *titoloNuovo, *titoloAttuale;
  2207. BOOL ascendente;
  2208. __block BOOL nuovoAscendente;
  2209. UIImage *image;
  2210. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2211. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2212. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2213. [self tableViewSelect:YES];
  2214. }
  2215. }];
  2216. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2217. ordinamento = _directoryOrder;
  2218. if ([ordinamento isEqualToString:@"fileName"]) {
  2219. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2220. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2221. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2222. nuovoOrdinamento = @"date";
  2223. }
  2224. if ([ordinamento isEqualToString:@"date"]) {
  2225. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2226. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2227. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2228. nuovoOrdinamento = @"fileName";
  2229. }
  2230. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2231. [self orderTable:nuovoOrdinamento];
  2232. }];
  2233. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2234. ascendente = [CCUtility getAscendingSettings];
  2235. if (ascendente) {
  2236. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2237. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2238. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2239. nuovoAscendente = false;
  2240. }
  2241. if (!ascendente) {
  2242. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2243. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2244. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2245. nuovoAscendente = true;
  2246. }
  2247. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2248. [self ascendingTable:nuovoAscendente];
  2249. }];
  2250. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2251. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2252. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2253. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2254. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2255. else [self tableGroupBy:@"alphabetic"];
  2256. }];
  2257. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2258. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2259. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2260. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2261. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2262. else [self tableGroupBy:@"typefile"];
  2263. }];
  2264. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2265. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2266. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2267. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2268. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2269. else [self tableGroupBy:@"date"];
  2270. }];
  2271. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2272. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2273. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2274. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2275. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2276. else [self directoryOnTop:YES];
  2277. }];
  2278. // REMENU --------------------------------------------------------------------------------------------------------------
  2279. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2280. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2281. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2282. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2283. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2284. app.reMainMenu.separatorHeight = 0.5;
  2285. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2286. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2287. app.reMainMenu.textColor = [UIColor blackColor];
  2288. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2289. app.reMainMenu.textShadowColor = nil;
  2290. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2291. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2292. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2293. app.reMainMenu.highlightedSeparatorColor = nil;
  2294. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2295. app.reMainMenu.highlightedTextShadowColor = nil;
  2296. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2297. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2298. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2299. app.reMainMenu.subtitleTextShadowColor = nil;
  2300. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2301. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2302. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2303. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2304. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2305. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2306. app.reMainMenu.borderWidth = 0.3;
  2307. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2308. app.reMainMenu.animationDuration = 0.2;
  2309. app.reMainMenu.closeAnimationDuration = 0.2;
  2310. app.reMainMenu.bounce = NO;
  2311. [app.reMainMenu setClosePreparationBlock:^{
  2312. // Backgroun reMenu (Gesture)
  2313. [_reMenuBackgroundView removeFromSuperview];
  2314. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2315. }];
  2316. }
  2317. - (void)toggleReMainMenu
  2318. {
  2319. if (app.reMainMenu.isOpen) {
  2320. [app.reMainMenu close];
  2321. } else {
  2322. [self createReMainMenu];
  2323. [app.reMainMenu showFromNavigationController:self.navigationController];
  2324. // Backgroun reMenu & (Gesture)
  2325. [self createReMenuBackgroundView:app.reMainMenu];
  2326. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2327. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2328. }
  2329. }
  2330. - (void)createReSelectMenu
  2331. {
  2332. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2333. app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"deleteSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2334. [self deleteFile];
  2335. }];
  2336. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2337. app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"moveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2338. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2339. }];
  2340. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2341. app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_folders_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2342. [self downloadSelectedFilesFolders];
  2343. }];
  2344. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2345. app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2346. [self saveSelectedFiles];
  2347. }];
  2348. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2349. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2350. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2351. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2352. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2353. app.reSelectMenu.separatorHeight = 0.5;
  2354. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2355. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2356. app.reSelectMenu.textColor = [UIColor blackColor];
  2357. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2358. app.reSelectMenu.textShadowColor = nil;
  2359. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2360. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2361. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2362. app.reSelectMenu.highlightedSeparatorColor = nil;
  2363. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2364. app.reSelectMenu.highlightedTextShadowColor = nil;
  2365. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2366. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2367. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2368. app.reSelectMenu.subtitleTextShadowColor = nil;
  2369. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2370. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2371. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2372. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2373. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2374. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2375. app.reSelectMenu.borderWidth = 0.3;
  2376. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2377. app.reSelectMenu.closeAnimationDuration = 0.2;
  2378. app.reSelectMenu.animationDuration = 0.2;
  2379. app.reSelectMenu.bounce = NO;
  2380. [app.reSelectMenu setClosePreparationBlock:^{
  2381. // Backgroun reMenu (Gesture)
  2382. [_reMenuBackgroundView removeFromSuperview];
  2383. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2384. }];
  2385. }
  2386. - (void)toggleReSelectMenu
  2387. {
  2388. if (app.reSelectMenu.isOpen) {
  2389. [app.reSelectMenu close];
  2390. } else {
  2391. [self createReSelectMenu];
  2392. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2393. // Backgroun reMenu & (Gesture)
  2394. [self createReMenuBackgroundView:app.reSelectMenu];
  2395. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2396. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2397. }
  2398. }
  2399. #pragma --------------------------------------------------------------------------------------------
  2400. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2401. #pragma --------------------------------------------------------------------------------------------
  2402. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2403. {
  2404. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2405. UITableView *tableView = (UITableView*)self.view;
  2406. CGPoint touchPoint = [recognizer locationInView:self.view];
  2407. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2408. if ([self indexPathIsValid:indexPath])
  2409. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2410. else
  2411. _metadata = nil;
  2412. [self becomeFirstResponder];
  2413. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2414. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2415. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2416. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2417. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2418. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2419. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2420. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2421. [menuController setMenuVisible:YES animated:YES];
  2422. }
  2423. }
  2424. - (BOOL)canBecomeFirstResponder
  2425. {
  2426. return YES;
  2427. }
  2428. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2429. {
  2430. // For copy file, copy files, Open in ... :
  2431. //
  2432. // NO Directory
  2433. // NO Error Passcode
  2434. // NO In Session mode (download/upload)
  2435. // NO Template
  2436. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2437. if (_isSelectedMode == NO && _metadata && !_metadata.directory && [_metadata.session length] == 0) return YES;
  2438. else return NO;
  2439. }
  2440. if (@selector(copyFiles:) == action) {
  2441. if (_isSelectedMode) {
  2442. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2443. for (tableMetadata *metadata in selectedMetadatas) {
  2444. if (!metadata.directory && metadata.session.length == 0)
  2445. return YES;
  2446. }
  2447. }
  2448. return NO;
  2449. }
  2450. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2451. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2452. NSArray *items = [pasteboard items];
  2453. if ([items count] == 1) {
  2454. // Value : (NSData) fileID
  2455. NSDictionary *dic = [items objectAtIndex:0];
  2456. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2457. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2458. if (fileID) {
  2459. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2460. if (metadata) {
  2461. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2462. if (account) {
  2463. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2464. if (directoryUser)
  2465. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2466. return YES;
  2467. }
  2468. }
  2469. }
  2470. }
  2471. return NO;
  2472. }
  2473. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2474. BOOL isValid = NO;
  2475. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2476. NSArray *items = [pasteboard items];
  2477. if ([items count] <= 1) return NO;
  2478. for (NSDictionary *dic in items) {
  2479. // Value : (NSData) fileID
  2480. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2481. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2482. if (fileID) {
  2483. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2484. if (metadata) {
  2485. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2486. if (account) {
  2487. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2488. if (directoryUser) {
  2489. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2490. isValid = YES;
  2491. } else {
  2492. isValid = NO;
  2493. break;
  2494. }
  2495. } else {
  2496. isValid = NO;
  2497. break;
  2498. }
  2499. } else {
  2500. isValid = NO;
  2501. break;
  2502. }
  2503. } else {
  2504. isValid = NO;
  2505. break;
  2506. }
  2507. } else {
  2508. isValid = NO;
  2509. break;
  2510. }
  2511. }
  2512. return isValid;
  2513. }
  2514. return NO;
  2515. }
  2516. /************************************ COPY ************************************/
  2517. - (void)copyFile:(id)sender
  2518. {
  2519. // Remove all item
  2520. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2521. pasteboard.items = [[NSArray alloc] init];
  2522. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2523. [self copyFileToPasteboard:_metadata];
  2524. } else {
  2525. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2526. if (serverUrl)
  2527. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2528. }
  2529. }
  2530. - (void)copyFiles:(id)sender
  2531. {
  2532. // Remove all item
  2533. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2534. pasteboard.items = [[NSArray alloc] init];
  2535. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2536. for (tableMetadata *metadata in selectedMetadatas) {
  2537. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2538. [self copyFileToPasteboard:metadata];
  2539. } else {
  2540. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2541. if (serverUrl)
  2542. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2543. }
  2544. }
  2545. [self tableViewSelect:NO];
  2546. }
  2547. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2548. {
  2549. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2550. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2551. // Value : (NSData) fileID
  2552. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2553. [items addObject:item];
  2554. [pasteboard setItems:items];
  2555. }
  2556. /************************************ OPEN IN ... ******************************/
  2557. - (void)openinFile:(id)sender
  2558. {
  2559. [self openIn:_metadata];
  2560. }
  2561. /************************************ PASTE ************************************/
  2562. - (void)pasteFile:(id)sender
  2563. {
  2564. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2565. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2566. }
  2567. - (void)pasteFileEncrypted:(id)sender
  2568. {
  2569. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2570. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2571. }
  2572. - (void)pasteFiles:(id)sender
  2573. {
  2574. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2575. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2576. }
  2577. - (void)pasteFilesEncrypted:(id)sender
  2578. {
  2579. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2580. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2581. }
  2582. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2583. {
  2584. float timer = 0;
  2585. for (NSDictionary *dic in items) {
  2586. // Value : (NSData) fileID
  2587. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2588. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2589. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2590. if (metadata) {
  2591. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2592. if (account) {
  2593. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2594. if (directoryUser) {
  2595. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2596. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName]];
  2597. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2598. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:_serverUrl session:k_upload_session taskStatus:k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  2599. });
  2600. timer += 0.1;
  2601. }
  2602. }
  2603. }
  2604. }
  2605. }
  2606. }
  2607. #pragma --------------------------------------------------------------------------------------------
  2608. #pragma mark ===== Lock Passcode =====
  2609. #pragma --------------------------------------------------------------------------------------------
  2610. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2611. {
  2612. return _failedAttempts;
  2613. }
  2614. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2615. {
  2616. return _lockUntilDate;
  2617. }
  2618. - (void)passcodeViewCloseButtonPressed:(id)sender
  2619. {
  2620. [self dismissViewControllerAnimated:YES completion:nil];
  2621. }
  2622. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2623. {
  2624. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2625. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2626. _lockUntilDate = nil;
  2627. _failedAttempts = 0;
  2628. aResultHandler(YES);
  2629. } else aResultHandler(NO);
  2630. } else aResultHandler(YES);
  2631. }
  2632. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2633. {
  2634. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2635. switch (aViewController.type) {
  2636. case BKPasscodeViewControllerCheckPasscodeType: {
  2637. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2638. // possiamo procedere alla prossima directory
  2639. [self performSegueDirectoryWithControlPasscode:false];
  2640. // avviamo la sessione Passcode Lock con now
  2641. app.sessionePasscodeLock = [NSDate date];
  2642. }
  2643. // disattivazione lock cartella
  2644. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2645. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2646. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2647. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2648. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2649. }
  2650. [self tableViewReloadData];
  2651. }
  2652. }
  2653. break;
  2654. default:
  2655. break;
  2656. }
  2657. }
  2658. - (void)comandoLockPassword
  2659. {
  2660. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2661. if (!serverUrl) return;
  2662. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2663. // se non è abilitato il Lock Passcode esci
  2664. if ([[CCUtility getBlockCode] length] == 0) {
  2665. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2666. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2667. [alertController addAction:okAction];
  2668. [self presentViewController:alertController animated:YES completion:nil];
  2669. return;
  2670. }
  2671. // se è richiesta la disattivazione si chiede la password
  2672. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2673. if (directory.lock) {
  2674. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2675. viewController.delegate = self;
  2676. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2677. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2678. viewController.inputViewTitlePassword = YES;
  2679. if ([CCUtility getSimplyBlockCode]) {
  2680. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2681. viewController.passcodeInputView.maximumLength = 6;
  2682. } else {
  2683. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2684. viewController.passcodeInputView.maximumLength = 64;
  2685. }
  2686. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2687. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2688. viewController.touchIDManager = touchIDManager;
  2689. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2690. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2691. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  2692. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2693. [self presentViewController:navigationController animated:YES completion:nil];
  2694. return;
  2695. }
  2696. // ---------------- ACTIVATE PASSWORD
  2697. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2698. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2699. if ([self indexPathIsValid:indexPath])
  2700. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2701. } else {
  2702. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2703. }
  2704. }
  2705. #pragma mark -
  2706. #pragma --------------------------------------------------------------------------------------------
  2707. #pragma mark ===== Swipe Tablet -> menu =====
  2708. #pragma --------------------------------------------------------------------------------------------
  2709. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2710. {
  2711. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2712. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2713. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2714. return NO;
  2715. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  2716. return NO;
  2717. else
  2718. return YES;
  2719. }
  2720. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2721. {
  2722. }
  2723. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2724. {
  2725. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2726. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2727. if (direction == MGSwipeDirectionRightToLeft) {
  2728. // Delete
  2729. if (index == 0)
  2730. [self swipeDelete:indexPath];
  2731. // More
  2732. if (index == 1)
  2733. [self swipeMore:indexPath];
  2734. }
  2735. if (direction == MGSwipeDirectionLeftToRight) {
  2736. if (_metadata.favorite)
  2737. [self removeFavorite:_metadata];
  2738. else
  2739. [self addFavorite:_metadata];
  2740. }
  2741. return YES;
  2742. }
  2743. - (void)swipeDelete:(NSIndexPath *)indexPath
  2744. {
  2745. // Directory locked ?
  2746. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileName];
  2747. if (!lockServerUrl) return;
  2748. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2749. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) {
  2750. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2751. return;
  2752. }
  2753. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2754. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2755. [self performSelector:@selector(deleteFile) withObject:nil];
  2756. }]];
  2757. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2758. [alertController dismissViewControllerAnimated:YES completion:nil];
  2759. }]];
  2760. alertController.popoverPresentationController.sourceView = self.view;
  2761. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2762. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2763. [alertController.view layoutIfNeeded];
  2764. [self presentViewController:alertController animated:YES completion:nil];
  2765. }
  2766. - (void)swipeMore:(NSIndexPath *)indexPath
  2767. {
  2768. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2769. if (!serverUrl) return;
  2770. NSString *titoloLock, *titleFavorite;
  2771. if (_metadata.favorite) {
  2772. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  2773. } else {
  2774. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  2775. }
  2776. if (_metadata.directory) {
  2777. // calcolo lockServerUrl
  2778. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2779. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2780. if (directory.lock)
  2781. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2782. else
  2783. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2784. }
  2785. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  2786. // ******************************************* AHKActionSheet *******************************************
  2787. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2788. actionSheet.animationDuration = 0.2;
  2789. actionSheet.buttonHeight = 50.0;
  2790. actionSheet.cancelButtonHeight = 50.0f;
  2791. actionSheet.separatorHeight = 5.0f;
  2792. actionSheet.automaticallyTintButtonImages = @(NO);
  2793. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].encrypted };
  2794. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2795. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  2796. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor darkGrayColor] };
  2797. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2798. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2799. // ******************************************* DIRECTORY *******************************************
  2800. if (_metadata.directory) {
  2801. BOOL lockDirectory = NO;
  2802. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2803. // Directory bloccata ?
  2804. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, dirServerUrl]];
  2805. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  2806. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  2807. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  2808. [actionSheet addButtonWithTitle: _metadata.fileName
  2809. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  2810. backgroundColor: [NCBrandColor sharedInstance].tabBar
  2811. height: 50.0
  2812. type: AHKActionSheetButtonTypeDisabled
  2813. handler: nil
  2814. ];
  2815. if (!lockDirectory) {
  2816. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2817. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  2818. backgroundColor:[UIColor whiteColor]
  2819. height: 50.0
  2820. type:AHKActionSheetButtonTypeDefault
  2821. handler:^(AHKActionSheet *as) {
  2822. [self openWindowShare:_metadata];
  2823. }];
  2824. }
  2825. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  2826. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2827. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  2828. backgroundColor:[UIColor whiteColor]
  2829. height: 50.0
  2830. type:AHKActionSheetButtonTypeDefault
  2831. handler:^(AHKActionSheet *as) {
  2832. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2833. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2834. textField.text = _metadata.fileName;
  2835. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  2836. //textField.delegate = self;
  2837. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2838. }];
  2839. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2840. NSLog(@"[LOG] Cancel action");
  2841. }];
  2842. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2843. UITextField *fileName = alertController.textFields.firstObject;
  2844. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  2845. }];
  2846. okAction.enabled = NO;
  2847. [alertController addAction:cancelAction];
  2848. [alertController addAction:okAction];
  2849. [self presentViewController:alertController animated:YES completion:nil];
  2850. }];
  2851. }
  2852. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  2853. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2854. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  2855. backgroundColor:[UIColor whiteColor]
  2856. height: 50.0
  2857. type:AHKActionSheetButtonTypeDefault
  2858. handler:^(AHKActionSheet *as) {
  2859. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2860. }];
  2861. }
  2862. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  2863. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  2864. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  2865. backgroundColor:[UIColor whiteColor]
  2866. height: 50.0
  2867. type:AHKActionSheetButtonTypeDefault
  2868. handler:^(AHKActionSheet *as) {
  2869. // Settings new folder Automatatic upload
  2870. NSString *oldAutoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  2871. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  2872. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:app.activeUrl];
  2873. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:oldAutoUploadDirectory directoryID:nil];
  2874. if (app.activeAccount.length > 0 && app.activePhotos)
  2875. [app.activePhotos reloadDatasourceForced];
  2876. [self readFolder:serverUrl];
  2877. NSLog(@"[LOG] Update Folder Photo");
  2878. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  2879. if ([autoUploadPath length] > 0) {
  2880. [[CCSynchronize sharedSynchronize] readFileForFolder:_metadata.fileName serverUrl:serverUrl selector:selectorReadFileFolder];
  2881. }
  2882. }];
  2883. }
  2884. #ifdef DEBUG
  2885. if ([CCUtility isEndToEndEnabled:app.activeAccount]) {
  2886. [actionSheet addButtonWithTitle:@"Mark as encrypted"
  2887. image:[UIImage imageNamed:@"actionSheetCrypto"]
  2888. backgroundColor:[UIColor whiteColor]
  2889. height: 50.0
  2890. type:AHKActionSheetButtonTypeEncrypted
  2891. handler:^(AHKActionSheet *as) {
  2892. [app.endToEndInterface markEndToEndFolderEncrypted:_metadata];
  2893. }];
  2894. }
  2895. if ([CCUtility isEndToEndEnabled:app.activeAccount]) {
  2896. [actionSheet addButtonWithTitle:@"Delete mark as encrypted"
  2897. image:[UIImage imageNamed:@"actionSheetCrypto"]
  2898. backgroundColor:[UIColor whiteColor]
  2899. height: 50.0
  2900. type:AHKActionSheetButtonTypeEncrypted
  2901. handler:^(AHKActionSheet *as) {
  2902. [app.endToEndInterface deletemarkEndToEndFolderEncrypted:_metadata];
  2903. }];
  2904. }
  2905. if ([CCUtility isEndToEndEnabled:app.activeAccount]) {
  2906. [actionSheet addButtonWithTitle:@"Lock file"
  2907. image:[UIImage imageNamed:@"actionSheetCrypto"]
  2908. backgroundColor:[UIColor whiteColor]
  2909. height: 50.0
  2910. type:AHKActionSheetButtonTypeEncrypted
  2911. handler:^(AHKActionSheet *as) {
  2912. [app.endToEndInterface lockEndToEndFolderEncrypted:_metadata];
  2913. }];
  2914. }
  2915. if ([CCUtility isEndToEndEnabled:app.activeAccount]) {
  2916. [actionSheet addButtonWithTitle:@"Unlock file"
  2917. image:[UIImage imageNamed:@"actionSheetCrypto"]
  2918. backgroundColor:[UIColor whiteColor]
  2919. height: 50.0
  2920. type:AHKActionSheetButtonTypeEncrypted
  2921. handler:^(AHKActionSheet *as) {
  2922. [app.endToEndInterface unlockEndToEndFolderEncrypted:_metadata];
  2923. }];
  2924. }
  2925. if ([CCUtility isEndToEndEnabled:app.activeAccount]) {
  2926. [actionSheet addButtonWithTitle:@"Get metadata file"
  2927. image:[UIImage imageNamed:@"actionSheetCrypto"]
  2928. backgroundColor:[UIColor whiteColor]
  2929. height: 50.0
  2930. type:AHKActionSheetButtonTypeEncrypted
  2931. handler:^(AHKActionSheet *as) {
  2932. [app.endToEndInterface getEndToEndMetadata:_metadata];
  2933. }];
  2934. }
  2935. #endif
  2936. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  2937. [actionSheet addButtonWithTitle:titoloLock
  2938. image:[UIImage imageNamed:@"actionSheetLock"]
  2939. backgroundColor:[UIColor whiteColor]
  2940. height: 50.0
  2941. type:AHKActionSheetButtonTypeEncrypted
  2942. handler:^(AHKActionSheet *as) {
  2943. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  2944. }];
  2945. }
  2946. [actionSheet show];
  2947. }
  2948. // ******************************************* FILE *******************************************
  2949. if (!_metadata.directory) {
  2950. UIImage *iconHeader;
  2951. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  2952. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  2953. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  2954. else
  2955. iconHeader = [UIImage imageNamed:_metadata.iconName];
  2956. [actionSheet addButtonWithTitle: _metadata.fileName
  2957. image: iconHeader
  2958. backgroundColor: [NCBrandColor sharedInstance].tabBar
  2959. height: 50.0
  2960. type: AHKActionSheetButtonTypeDisabled
  2961. handler: nil
  2962. ];
  2963. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2964. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"]color:[NCBrandColor sharedInstance].brand]
  2965. backgroundColor:[UIColor whiteColor]
  2966. height: 50.0
  2967. type:AHKActionSheetButtonTypeDefault
  2968. handler:^(AHKActionSheet *as) {
  2969. [self openWindowShare:_metadata];
  2970. }];
  2971. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  2972. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  2973. backgroundColor:[UIColor whiteColor]
  2974. height: 50.0
  2975. type:AHKActionSheetButtonTypeDefault
  2976. handler:^(AHKActionSheet *as) {
  2977. [self performSelector:@selector(openIn:) withObject:_metadata];
  2978. }];
  2979. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2980. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  2981. backgroundColor:[UIColor whiteColor]
  2982. height: 50.0
  2983. type:AHKActionSheetButtonTypeDefault
  2984. handler:^(AHKActionSheet *as) {
  2985. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2986. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2987. textField.text = _metadata.fileName;
  2988. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2989. }];
  2990. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2991. NSLog(@"[LOG] Cancel action");
  2992. }];
  2993. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2994. UITextField *fileName = alertController.textFields.firstObject;
  2995. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  2996. }];
  2997. okAction.enabled = NO;
  2998. [alertController addAction:cancelAction];
  2999. [alertController addAction:okAction];
  3000. [self presentViewController:alertController animated:YES completion:nil];
  3001. }];
  3002. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3003. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3004. backgroundColor:[UIColor whiteColor]
  3005. height: 50.0
  3006. type:AHKActionSheetButtonTypeDefault
  3007. handler:^(AHKActionSheet *as) {
  3008. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3009. }];
  3010. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3011. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3012. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3013. backgroundColor:[UIColor whiteColor]
  3014. height: 50.0
  3015. type:AHKActionSheetButtonTypeDefault
  3016. handler:^(AHKActionSheet *as) {
  3017. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3018. }];
  3019. }
  3020. [actionSheet show];
  3021. }
  3022. }
  3023. #pragma --------------------------------------------------------------------------------------------
  3024. #pragma mark - ==== Datasource ====
  3025. #pragma --------------------------------------------------------------------------------------------
  3026. - (void)clearDateReadDataSource:(NSNotification *)notification
  3027. {
  3028. _dateReadDataSource = Nil;
  3029. [self reloadDatasource];
  3030. }
  3031. - (void)reloadDatasource
  3032. {
  3033. [self reloadDatasource:_serverUrl];
  3034. }
  3035. - (void)reloadDatasource:(NSString *)serverUrl
  3036. {
  3037. // test
  3038. if (app.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil)
  3039. return;
  3040. // Search Mode
  3041. if(_isSearchMode) {
  3042. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy activeAccount:app.activeAccount];
  3043. [self tableViewReloadData];
  3044. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3045. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3046. _noFilesSearchDescription = @"";
  3047. }
  3048. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3049. _noFilesSearchTitle = @"";
  3050. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3051. }
  3052. [self.tableView reloadEmptyDataSet];
  3053. return;
  3054. }
  3055. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3056. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3057. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3058. if (main) {
  3059. [main reloadDatasource];
  3060. } else {
  3061. [self tableViewReloadData];
  3062. [app.activeTransfers reloadDatasource];
  3063. }
  3064. return;
  3065. }
  3066. [app.activeTransfers reloadDatasource];
  3067. // Settaggio variabili per le ottimizzazioni
  3068. _directoryGroupBy = [CCUtility getGroupBySettings];
  3069. _directoryOrder = [CCUtility getOrderSettings];
  3070. // Controllo data lettura Data Source
  3071. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  3072. NSDate *dateDateRecordDirectory = directory.dateReadDirectory;
  3073. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3074. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3075. _dateReadDataSource = [NSDate date];
  3076. // Data Source
  3077. NSString *sorted = _directoryOrder;
  3078. if ([sorted isEqualToString:@"fileName"])
  3079. sorted = @"fileName";
  3080. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  3081. if (directoryID) {
  3082. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND status = %i", app.activeAccount, directoryID, k_metadataStatusNormal] sorted:sorted ascending:[CCUtility getAscendingSettings]];
  3083. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3084. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy activeAccount:app.activeAccount];
  3085. }
  3086. } else {
  3087. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3088. }
  3089. [self tableViewReloadData];
  3090. }
  3091. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3092. {
  3093. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3094. if (selectedRows.count > 0) {
  3095. for (NSIndexPath *selectionIndex in selectedRows) {
  3096. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3097. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3098. [metadatas addObject:metadata];
  3099. }
  3100. }
  3101. return metadatas;
  3102. }
  3103. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3104. {
  3105. NSInteger section = indexPath.section + 1;
  3106. NSInteger row = indexPath.row + 1;
  3107. NSInteger totSections = [_sectionDataSource.sections count] ;
  3108. if ((totSections < section) || (section > totSections)) {
  3109. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3110. return nil;
  3111. }
  3112. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3113. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3114. if (fileIDs) {
  3115. NSInteger totRows =[fileIDs count] ;
  3116. if ((totRows < row) || (row > totRows)) {
  3117. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3118. return nil;
  3119. }
  3120. } else {
  3121. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3122. return nil;
  3123. }
  3124. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3125. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3126. return metadata;
  3127. }
  3128. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3129. {
  3130. NSInteger totSections =[_sectionDataSource.sections count] ;
  3131. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3132. return nil;
  3133. }
  3134. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3135. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3136. }
  3137. #pragma --------------------------------------------------------------------------------------------
  3138. #pragma mark - ==== Table ====
  3139. #pragma --------------------------------------------------------------------------------------------
  3140. - (void)tableViewSelect:(BOOL)edit
  3141. {
  3142. // chiudiamo eventuali swipe aperti
  3143. if (edit)
  3144. [self.tableView setEditing:NO animated:NO];
  3145. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3146. [self.tableView setEditing:edit animated:YES];
  3147. _isSelectedMode = edit;
  3148. if (edit)
  3149. [self setUINavigationBarSelected];
  3150. else
  3151. [self setUINavigationBarDefault];
  3152. [_selectedFileIDsMetadatas removeAllObjects];
  3153. [self setTitle];
  3154. }
  3155. - (void)tableViewReloadData
  3156. {
  3157. // store selected cells before relod
  3158. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3159. //store swipeOffset before relod
  3160. [_statusSwipeCell removeAllObjects];
  3161. for (MGSwipeTableCell *cell in self.tableView.visibleCells) {
  3162. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  3163. [_statusSwipeCell setObject:[NSNumber numberWithDouble:cell.swipeOffset] forKey:indexPath];
  3164. }
  3165. // reload table view
  3166. [self.tableView reloadData];
  3167. // selected cells stored
  3168. for (NSIndexPath *path in indexPaths)
  3169. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3170. [self setTableViewFooter];
  3171. if (self.tableView.editing)
  3172. [self setTitle];
  3173. }
  3174. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3175. {
  3176. if (tableView.editing == 1) {
  3177. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3178. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3179. return NO;
  3180. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  3181. return NO;
  3182. else
  3183. return YES;
  3184. } else {
  3185. [_selectedFileIDsMetadatas removeAllObjects];
  3186. }
  3187. return YES;
  3188. }
  3189. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3190. {
  3191. return 60;
  3192. }
  3193. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3194. {
  3195. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3196. }
  3197. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3198. {
  3199. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3200. }
  3201. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3202. {
  3203. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3204. NSString *sectionTitle = [sections objectAtIndex:section];
  3205. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3206. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3207. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3208. return 20.f;
  3209. }
  3210. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3211. {
  3212. float shift;
  3213. UIVisualEffectView *visualEffectView;
  3214. NSString *titleSection;
  3215. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  3216. return nil;
  3217. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  3218. titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3219. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  3220. titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3221. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3222. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3223. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3224. else titleSection = NSLocalizedString(titleSection,nil);
  3225. // Format title
  3226. NSString *currentDevice = [CCUtility currentDevice];
  3227. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3228. visualEffectView = [[UIVisualEffectView alloc] init];
  3229. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3230. } else {
  3231. UIVisualEffect *blurEffect;
  3232. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3233. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3234. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3235. }
  3236. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3237. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3238. shift = - 35;
  3239. else
  3240. shift = - 20;
  3241. } else shift = - 10;
  3242. // Title
  3243. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3244. titleLabel.backgroundColor = [UIColor clearColor];
  3245. titleLabel.textColor = [UIColor blackColor];
  3246. titleLabel.font = [UIFont systemFontOfSize:12];
  3247. titleLabel.textAlignment = NSTextAlignmentLeft;
  3248. titleLabel.text = titleSection;
  3249. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3250. [visualEffectView.contentView addSubview:titleLabel];
  3251. // Elements
  3252. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3253. elementLabel.backgroundColor = [UIColor clearColor];
  3254. elementLabel.textColor = [UIColor blackColor];;
  3255. elementLabel.font = [UIFont systemFontOfSize:12];
  3256. elementLabel.textAlignment = NSTextAlignmentRight;
  3257. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3258. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3259. NSUInteger rowsCount = [metadatas count];
  3260. if (rowsCount == 0) return nil;
  3261. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3262. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3263. [visualEffectView.contentView addSubview:elementLabel];
  3264. return visualEffectView;
  3265. }
  3266. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3267. {
  3268. return [_sectionDataSource.sections indexOfObject:title];
  3269. }
  3270. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3271. {
  3272. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3273. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3274. else
  3275. return nil;
  3276. }
  3277. /*
  3278. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3279. {
  3280. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3281. }
  3282. }
  3283. */
  3284. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3285. {
  3286. NSString *typeCell;
  3287. NSString *dataFile;
  3288. NSString *lunghezzaFile;
  3289. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3290. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3291. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3292. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3293. if (!serverUrl)
  3294. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3295. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3296. else typeCell = @"CellMainTransfer";
  3297. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3298. // variable base
  3299. cell.delegate = self;
  3300. cell.indexPath = indexPath;
  3301. // separator
  3302. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3303. // change color selection
  3304. UIView *selectionColor = [[UIView alloc] init];
  3305. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3306. cell.selectedBackgroundView = selectionColor;
  3307. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3308. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3309. // ----------------------------------------------------------------------------------------------------------
  3310. // DEFAULT
  3311. // ----------------------------------------------------------------------------------------------------------
  3312. cell.file.image = nil;
  3313. cell.status.image = nil;
  3314. cell.favorite.image = nil;
  3315. cell.shared.image = nil;
  3316. cell.local.image = nil;
  3317. cell.labelTitle.enabled = YES;
  3318. cell.labelTitle.text = @"";
  3319. cell.labelInfoFile.enabled = YES;
  3320. cell.labelInfoFile.text = @"";
  3321. cell.progressView.progress = 0.0;
  3322. cell.progressView.hidden = YES;
  3323. cell.cancelTaskButton.hidden = YES;
  3324. cell.reloadTaskButton.hidden = YES;
  3325. cell.stopTaskButton.hidden = YES;
  3326. cell.labelTitle.textColor = [UIColor blackColor];
  3327. // ----------------------------------------------------------------------------------------------------------
  3328. // File Name & Folder
  3329. // ----------------------------------------------------------------------------------------------------------
  3330. // nome del file
  3331. cell.labelTitle.text = metadata.fileName;
  3332. // è una directory
  3333. if (metadata.directory) {
  3334. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3335. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3336. lunghezzaFile = @" ";
  3337. // ----------------------------------------------------------------------------------------------------------
  3338. // Favorite Folder
  3339. // ----------------------------------------------------------------------------------------------------------
  3340. if (metadata.favorite) {
  3341. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3342. }
  3343. } else {
  3344. // File
  3345. dataFile = [CCUtility dateDiff:metadata.date];
  3346. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3347. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3348. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3349. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3350. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3351. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3352. cell.local.image = [UIImage imageNamed:@"local"];
  3353. else
  3354. cell.local.image = nil;
  3355. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", dataFile, lunghezzaFile];
  3356. cell.accessoryType = UITableViewCellAccessoryNone;
  3357. }
  3358. // ----------------------------------------------------------------------------------------------------------
  3359. // File Image View
  3360. // ----------------------------------------------------------------------------------------------------------
  3361. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3362. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3363. cell.file.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  3364. } else {
  3365. if (metadata.directory) {
  3366. if (metadata.encrypted)
  3367. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[UIColor redColor]];
  3368. else
  3369. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3370. } else {
  3371. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3372. }
  3373. if (metadata.thumbnailExists)
  3374. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3375. }
  3376. // ----------------------------------------------------------------------------------------------------------
  3377. // Image Status cyptated & Lock Passcode
  3378. // ----------------------------------------------------------------------------------------------------------
  3379. // Directory con passcode lock attivato
  3380. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  3381. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3382. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3383. cell.status.image = [UIImage imageNamed:@"passcode"];
  3384. // ----------------------------------------------------------------------------------------------------------
  3385. // Favorite
  3386. // ----------------------------------------------------------------------------------------------------------
  3387. if (metadata.favorite) {
  3388. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3389. }
  3390. // ----------------------------------------------------------------------------------------------------------
  3391. // Share
  3392. // ----------------------------------------------------------------------------------------------------------
  3393. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3394. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3395. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3396. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3397. // Aggiungiamo il Tap per le shared
  3398. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3399. // Shared with you
  3400. if (isShare) {
  3401. if (metadata.directory) {
  3402. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3403. cell.accessoryType = UITableViewCellAccessoryNone;
  3404. }
  3405. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3406. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3407. [tap setNumberOfTapsRequired:1];
  3408. cell.shared.userInteractionEnabled = YES;
  3409. [cell.shared addGestureRecognizer:tap];
  3410. }
  3411. // Mounted with you
  3412. if (isMounted) {
  3413. if (metadata.directory) {
  3414. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3415. cell.accessoryType = UITableViewCellAccessoryNone;
  3416. }
  3417. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3418. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3419. [tap setNumberOfTapsRequired:1];
  3420. cell.shared.userInteractionEnabled = YES;
  3421. [cell.shared addGestureRecognizer:tap];
  3422. }
  3423. // You share
  3424. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3425. if (metadata.directory) {
  3426. if ([shareLink length] > 0)
  3427. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3428. if ([shareUserAndGroup length] > 0)
  3429. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3430. cell.shared.userInteractionEnabled = NO;
  3431. } else {
  3432. if ([shareLink length] > 0)
  3433. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3434. if ([shareUserAndGroup length] > 0)
  3435. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3436. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3437. [tap setNumberOfTapsRequired:1];
  3438. cell.shared.userInteractionEnabled = YES;
  3439. [cell.shared addGestureRecognizer:tap];
  3440. }
  3441. }
  3442. } else {
  3443. cell.shared.userInteractionEnabled = NO;
  3444. }
  3445. // ----------------------------------------------------------------------------------------------------------
  3446. // downloadFile
  3447. // ----------------------------------------------------------------------------------------------------------
  3448. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3449. cell.status.image = [UIImage imageNamed:@"statusdownload"];
  3450. // sessionTaskIdentifier : RELOAD + STOP
  3451. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3452. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3453. cell.cancelTaskButton.hidden = NO;
  3454. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3455. cell.reloadTaskButton.hidden = NO;
  3456. }
  3457. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3458. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3459. if (progress > 0) {
  3460. cell.progressView.progressTintColor = [UIColor blackColor];
  3461. cell.progressView.progress = progress;
  3462. cell.progressView.hidden = NO;
  3463. }
  3464. // ----------------------------------------------------------------------------------------------------------
  3465. // downloadFile Error
  3466. // ----------------------------------------------------------------------------------------------------------
  3467. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3468. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3469. if ([metadata.sessionError length] == 0)
  3470. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3471. else
  3472. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3473. }
  3474. }
  3475. // ----------------------------------------------------------------------------------------------------------
  3476. // uploadFile
  3477. // ----------------------------------------------------------------------------------------------------------
  3478. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3479. cell.status.image = [UIImage imageNamed:@"statusupload"];
  3480. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3481. cell.cancelTaskButton.hidden = NO;
  3482. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3483. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3484. cell.status.image = [UIImage imageNamed:@"statusstop"];
  3485. cell.reloadTaskButton.hidden = NO;
  3486. cell.stopTaskButton.hidden = YES;
  3487. } else {
  3488. [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3489. cell.stopTaskButton.hidden = NO;
  3490. cell.reloadTaskButton.hidden = YES;
  3491. }
  3492. // se non c'è una preview in bianconero metti l'immagine di default
  3493. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3494. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3495. cell.labelTitle.enabled = NO;
  3496. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3497. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3498. if (progress > 0) {
  3499. cell.progressView.progressTintColor = [UIColor blackColor];
  3500. cell.progressView.progress = progress;
  3501. cell.progressView.hidden = NO;
  3502. }
  3503. // ----------------------------------------------------------------------------------------------------------
  3504. // uploadFileError
  3505. // ----------------------------------------------------------------------------------------------------------
  3506. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3507. cell.labelTitle.enabled = NO;
  3508. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3509. if ([metadata.sessionError length] == 0)
  3510. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3511. else
  3512. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3513. }
  3514. }
  3515. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3516. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3517. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3518. // ======== MGSwipe ========
  3519. if (metadata.favorite)
  3520. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_unfavorite_", nil)] icon:[UIImage imageNamed:@"swipeUnfavorite"] backgroundColor:[UIColor colorWithRed:242.0/255.0 green:220.0/255.0 blue:132.0/255.0 alpha:1.000]]];
  3521. else
  3522. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_favorite_", nil)] icon:[UIImage imageNamed:@"swipeFavorite"] backgroundColor:[UIColor colorWithRed:242.0/255.0 green:220.0/255.0 blue:132.0/255.0 alpha:1.000]]];
  3523. cell.leftExpansion.buttonIndex = 0;
  3524. cell.leftExpansion.fillOnTrigger = NO;
  3525. //centerIconOverText
  3526. MGSwipeButton *favoriteButton = (MGSwipeButton *)[cell.leftButtons objectAtIndex:0];
  3527. [favoriteButton centerIconOverText];
  3528. //Right
  3529. cell.rightButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_delete_", nil)] icon:[UIImage imageNamed:@"swipeDelete"] backgroundColor:[UIColor redColor]], [MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_more_", nil)] icon:[UIImage imageNamed:@"swipeMore"] backgroundColor:[UIColor lightGrayColor]]];
  3530. cell.rightSwipeSettings.transition = MGSwipeTransitionBorder;
  3531. //centerIconOverText
  3532. MGSwipeButton *deleteButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:0];
  3533. MGSwipeButton *moreButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:1];
  3534. [deleteButton centerIconOverText];
  3535. [moreButton centerIconOverText];
  3536. //restore swipeOffset after relod
  3537. CGFloat swipeOffset = [[_statusSwipeCell objectForKey:indexPath] doubleValue];
  3538. if (swipeOffset < 0) {
  3539. [cell showSwipe:MGSwipeDirectionRightToLeft animated:NO];
  3540. [_statusSwipeCell removeObjectForKey:indexPath];
  3541. } else if (swipeOffset > 0) {
  3542. [cell showSwipe:MGSwipeDirectionLeftToRight animated:NO];
  3543. [_statusSwipeCell removeObjectForKey:indexPath];
  3544. }
  3545. return cell;
  3546. }
  3547. - (void)setTableViewFooter
  3548. {
  3549. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3550. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3551. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3552. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3553. UIFont *appFont = [UIFont systemFontOfSize:12];
  3554. footerLabel.font = appFont;
  3555. footerLabel.textColor = [UIColor grayColor];
  3556. footerLabel.backgroundColor = [UIColor clearColor];
  3557. footerLabel.textAlignment = NSTextAlignmentCenter;
  3558. NSString *folders;
  3559. NSString *files;
  3560. NSString *footerText;
  3561. if (_sectionDataSource.directories > 1) {
  3562. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3563. } else if (_sectionDataSource.directories == 1){
  3564. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3565. } else {
  3566. folders = @"";
  3567. }
  3568. if (_sectionDataSource.files > 1) {
  3569. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3570. } else if (_sectionDataSource.files == 1){
  3571. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3572. } else {
  3573. files = @"";
  3574. }
  3575. if ([folders isEqualToString:@""]) {
  3576. footerText = files;
  3577. } else if ([files isEqualToString:@""]) {
  3578. footerText = folders;
  3579. } else {
  3580. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3581. }
  3582. footerLabel.text = footerText;
  3583. [footerView addSubview:footerLabel];
  3584. [self.tableView setTableFooterView:footerView];
  3585. }
  3586. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3587. {
  3588. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3589. // settiamo il record file.
  3590. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3591. if (!_metadata)
  3592. return;
  3593. // se non può essere selezionata deseleziona
  3594. if ([cell isEditing] == NO)
  3595. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3596. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3597. if (self.tableView.editing) {
  3598. [_selectedFileIDsMetadatas setObject:_metadata forKey:_metadata.fileID];
  3599. [self setTitle];
  3600. return;
  3601. }
  3602. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3603. if (!serverUrl) return;
  3604. // se è in corso una sessione
  3605. if ([_metadata.session length] > 0) return;
  3606. // file
  3607. if (_metadata.directory == NO) {
  3608. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3609. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3610. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3611. } else {
  3612. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3613. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3614. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3615. }
  3616. }
  3617. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3618. }
  3619. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3620. {
  3621. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3622. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3623. [self setTitle];
  3624. }
  3625. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3626. {
  3627. if (!indexPath)
  3628. return NO;
  3629. NSInteger section = indexPath.section;
  3630. NSInteger row = indexPath.row;
  3631. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3632. if (section > lastSectionIndex || lastSectionIndex < 0)
  3633. return NO;
  3634. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3635. if (rowCount < 0)
  3636. return NO;
  3637. return row <= rowCount;
  3638. }
  3639. #pragma --------------------------------------------------------------------------------------------
  3640. #pragma mark ===== Navigation ====
  3641. #pragma --------------------------------------------------------------------------------------------
  3642. - (BOOL)shouldPerformSegue
  3643. {
  3644. // if background return
  3645. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  3646. if (self.view.window == NO)
  3647. return NO;
  3648. // Collapsed ma siamo già in detail esci
  3649. if (self.splitViewController.isCollapsed)
  3650. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  3651. return YES;
  3652. }
  3653. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3654. {
  3655. id viewController = segue.destinationViewController;
  3656. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  3657. tableMetadata *metadata;
  3658. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3659. UINavigationController *nav = viewController;
  3660. _detailViewController = (CCDetail *)nav.topViewController;
  3661. } else {
  3662. _detailViewController = segue.destinationViewController;
  3663. }
  3664. if ([sender isKindOfClass:[tableMetadata class]]) {
  3665. metadata = sender;
  3666. [allRecordsDataSourceImagesVideos addObject:sender];
  3667. } else {
  3668. metadata = _metadata;
  3669. for (NSString *fileID in _sectionDataSource.allEtag) {
  3670. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3671. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [metadata.typeFile isEqualToString: k_metadataTypeFile_audio])
  3672. [allRecordsDataSourceImagesVideos addObject:metadata];
  3673. }
  3674. }
  3675. _detailViewController.metadataDetail = metadata;
  3676. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  3677. _detailViewController.dateFilterQuery = nil;
  3678. [_detailViewController setTitle:metadata.fileName];
  3679. }
  3680. // can i go to next viewcontroller
  3681. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  3682. {
  3683. NSString *nomeDir;
  3684. if(self.tableView.editing == NO) {
  3685. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3686. if (!serverUrl) return;
  3687. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  3688. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3689. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  3690. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  3691. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3692. viewController.delegate = self;
  3693. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3694. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3695. viewController.inputViewTitlePassword = YES;
  3696. if ([CCUtility getSimplyBlockCode]) {
  3697. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3698. viewController.passcodeInputView.maximumLength = 6;
  3699. } else {
  3700. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3701. viewController.passcodeInputView.maximumLength = 64;
  3702. }
  3703. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3704. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3705. viewController.touchIDManager = touchIDManager;
  3706. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3707. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3708. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  3709. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3710. [self presentViewController:navController animated:YES completion:nil];
  3711. return;
  3712. }
  3713. nomeDir = _metadata.fileName;
  3714. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  3715. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  3716. if (!viewController) {
  3717. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  3718. viewController.serverUrl = serverUrlPush;
  3719. viewController.titleMain = _metadata.fileName;
  3720. viewController.textBackButton = _titleMain;
  3721. // save self
  3722. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  3723. [self.navigationController pushViewController:viewController animated:YES];
  3724. } else {
  3725. if (viewController.isViewLoaded) {
  3726. // Fix : Application tried to present modally an active controller
  3727. if ([self.navigationController isBeingPresented]) {
  3728. // being presented
  3729. } else if ([self.navigationController isMovingToParentViewController]) {
  3730. // being pushed
  3731. } else {
  3732. [self.navigationController pushViewController:viewController animated:YES];
  3733. }
  3734. }
  3735. }
  3736. }
  3737. }
  3738. @end