CCMain.m 230 KB

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