CCMain.m 227 KB

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