CCMain.m 227 KB

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